【发布时间】:2021-03-13 00:37:15
【问题描述】:
所以我最近开始学习 ReactJS,并且一直在努力处理组件的状态。 在获取 URL 时,我收到一个 JSON 文件并将我的组件的状态设置为具有基于此 JSON 文件的值。如果我的状态键只接收一个值,我这样做没有问题,但我不知道如何循环通过我的 setState 以便我可以将多个值返回到我的状态键之一。 例如,如果 JSON 有一组成分,我只能将一种成分传递给我的状态成分数组,而不是全部。 总之,我想做这样的事情:
for(let i = 0; i < json.ingredients.length; i++) {
this.setState({
ingredients: [...this.state.ingredients, json.ingredients[i].name]
})
}
这是迄今为止我用来创建组件的代码:
class SingleMeal extends Component {
state = {
meal: null,
diets: [],
ingredients: []
}
componentDidMount() {
const { id } = this.props.match.params;
const url = `https://api.spoonacular.com/recipes/${id}/information?apiKey='apiKey`;
fetch(url)
.then( response => response.json())
.then ( json => (
this.setState({
meal: json,
diets: json.diets[0], // ADD ALL DIETS TO THIS STATE OBJECT
ingredients: [json.extendedIngredients[0].name] // ADD ALL INGREDIENTS TO THIS STATE OBJECT
})
))
}
感谢您的帮助!
【问题讨论】:
标签: reactjs components this