我能够使用 fetch 在本地导入 api JSON,如果您想查看它,可以在此url 中使用该 api 。
问题如下,在传递状态 searchString 时,我收到以下错误:
“类型错误:无法读取属性”映射“未定义”
我相信这是因为我正在导入完整的 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>
)
}