获取 URL 数据并循环访问它以将其推送到组件的状态数组 - ReactJS



所以我最近开始学习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
})
))
}
我很感激你的帮助!

如果你想添加json中的所有项目。节食,并且只从json中选择名称。extendedIngredients,试试这个:

this.setState({ 
meal: json,
diets: json.diets,
ingredients: json.extendedIngredients.map(ingredient=>ingredient.name)  
})

同时,我希望这不是你在url

中的实际api密钥

最新更新