使用JSON提取调用中的嵌套对象设置反应状态

时间:2020-03-22 12:19:37

标签: javascript json reactjs

我正在从食谱应用程序和id中提取食谱,例如,将返回的json结果中的某些对象插入到具有setstate的状态中。我知道如何执行这些操作之一,但是我在弄清楚如何将结果映射到我的状态时遇到了麻烦。有人可以帮我吗?

问题的代码在这里。我已经更改了我的api密钥和代码以确保安全性

componentDidMount() {
        let url = `https://api.edamam.com/search?q=banana&app_id=chjhvje1&app_key=b67djhhvhvhaef`;
        fetch(url)
            .then((response) => {
                return response.json();
            })
            .then((data) => {
                let recipeUIState = [ ...this.state.RecipeUI ];
                recipeUIState[0].title = data.hits[0].recipe.label;
                recipeUIState[0].thumbnail = data.hits[0].recipe.image;
                recipeUIState[0].href = data.hits[0].recipe.url;

                this.setState({ RecipeUI: recipeUIState });

                console.log(data.hits[0].recipe);
            });
    }

状态如下-

export default class RecipeUI extends Component {
    constructor(props) {
        super(props);
        this.state = {
            food: '',
            RecipeUI: [ { title: '' } ]
            // thumbnail: '', ingredients: '', href: ''
        };
        this.search = this.search.bind(this);
    }
来自API的

响应作为图像json response

附加

1 个答案:

答案 0 :(得分:0)

data.hits.forEach(({ recipe }) => {
  // We get the original state every before it's updated in the iteration
  const recipeUIState = [...this.state.RecipeUI];
  // Check if there's an existing recipe with the same title
  const idx = recipeUIState.findIndex(r => r.title === recipe.title);

  // Helper object to create a recipe from the current iteration
  const currentRecipe = {
    title: recipe.label,
    thumbnail: recipe.image,
    href: recipe.url
  };

  // `findIndex` returns -1 if no entry was found, otherwise it returns the index
  if (idx < 0) {
    // No existing recipe was found, append the new recipe to the original state
    return this.setState({
      recipeUIState: [...recipeUIState, ...currentRecipe]
    });
  }

  // Recipe already existed, create a new recipe by overwriting
  // the object at the index we found earlier
  const newRecipeUIState = {
    ...recipeUIState[idx],
    ...currentRecipe
  };

  // Replace the recipe at found index
  recipeUIState[idx] = newRecipeUIState;

  this.setState({ recipeUIState });
});

像这样?可以使用Array#reduce进行简化,但我不太习惯使用它。