gpt4 book ai didi

javascript - 类型错误 : Cannot read property 'map' of undefined - how to access an array in a local json API

转载 作者:行者123 更新时间:2023-11-30 14:05:42 25 4
gpt4 key购买 nike

我能够使用 fetch 在本地导入一个 api JSON,该 api 在 this 中可用。 url 如果你想查看它。

问题如下,在传递状态 searchString 时出现以下错误:

'TypeError: Can not read property' map 'of undefined'

我认为这是因为我正在导入完整的 json 对象,而我只需要访问关键结果。

File App.js

class App extends Component {
constructor(props) {
super(props);
this.state = {
searchString: []
};
}

componentDidMount() {
fetch('./recipes.json')
.then(response => response.json())
.then(json => console.log(json ))
.then(json => this.setState({ searchString: json }));
}

render() {
return (
<div className="App">
<Navbar />
<div className="container mt-10">
<div className="row">
<RecipeItem list={this.state.searchString}/>
</div>
</div>
</div>
);
}
}

File RecipeItem.js

const RecipeList = ({ searchString }) => {
<div>
<img className="card-img-top img-fluid" src={searchString.href} alt={searchString.title} />
<div className="card-body">
<h5 className="card-title">{searchString.title}</h5>
<p className="card-text">
<strong>Ingredients: </strong>{searchString.ingredients}
</p>
</div>
</div>
}

const RecipeItem = (props) => {
return (
<div className="col-sm-3 mt-4">
<div className="card">
{props.list.map((searchString, index) =>
<RecipeList searchString = {searchString} key={index} />
)}
</div>
</div>
)
}

最佳答案

RecipeItem 组件在最初安装时没有数据,因为您正在进行提取调用。这就是您收到错误的原因。

如果你有数据,你可以添加一个简单的检查,然后做 map /过滤器/或其他任何事情:

{props.list && props.list.map((searchString, index) =>
<RecipeList searchString = {searchString} key={index} />
)}

关于javascript - 类型错误 : Cannot read property 'map' of undefined - how to access an array in a local json API,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55435475/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com