【问题标题】:Fetching URL data and looping through it to push it to a component's state array - ReactJS获取 URL 数据并循环通过它以将其推送到组件的状态数组 - ReactJS
【发布时间】: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


    【解决方案1】:

    如果您想在 json.diets 中添加所有项目,并且只选择 json.extendedIngredients 中的名称,试试这个:

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

    另外,我希望这不是您在 url 中的实际 api 密钥

    【讨论】:

    • 也感谢您指出我的 api 密钥已发布,我从文件中复制和粘贴时没有注意到。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2017-06-22
    • 2016-06-19
    • 2021-07-17
    • 2019-11-02
    • 2011-04-11
    • 1970-01-01
    • 2016-03-26
    相关资源
    最近更新 更多