使用 react axios setState 渲染循环错误

Rendering loop error with react axios setState

我在虚拟文件夹中有不同的成分(伏特加、杜松子酒、威士忌...)json 文件。 我有一个 IngredientList.js,其中我 select 一种成分并将其传递给 IngredientSearch.js

IngredientSearch.js根据成分名称获取相关的json文件,然后我将ingredientRes的状态设置为res.data.drinks

我遇到的问题是,当我打印 console.log(newVals) --> 控制台从 json 无限地 记录数组。好像我在无限地重新渲染某些东西。

我的设置有什么问题?

IngredientSearch.js:

import React, { Component } from 'react';
import axios from 'axios';

class IngredientSearch extends Component {
    constructor() {
        super();
        this.state = {
            ingredientRes: []
        };
    }
    componentDidUpdate(prevProps) {
        let ingredient = this.props.ingredient;  //for example: vodka
        this.getIngredient_drinks(ingredient);
    }
    getIngredient_drinks = (ingredient) => {
        if(ingredient !== null) {
            axios.get(`../dummy/${ingredient}.json`)
                .then((res)=>{
                    let newVals = [];
                    newVals.push(res.data.drinks);
                    //console.log(newVals); // keeps relogging the arrays
                    this.setState({ ingredientRes: newVals });
                }).catch((err)=>{
                    console.log(err);
                })
        }
    }
    render() { 
        return (
            <div>
                IngredientSearch Results
                I want to map the ingredientRes here
            </div>
        )
    }
}
export default IngredientSearch;

您可以在 componentDidUpdate() 中立即调用 setState(),但请注意,它必须包含在类似 -

的条件中
if (this.props.ingredient !== prevProps.ingredient) {
    this.getIngredient_drinks(ingredient);
  }

否则会死循环

供参考 - https://reactjs.org/docs/react-component.html#componentdidupdate