TypeError: Cannot read property 'getIngredients' of undefined

TypeError: Cannot read property 'getIngredients' of undefined

我正在尝试根据 API 请求动态创建按钮。我已经将食物添加到一个对象中,现在我正在使用地图函数动态创建 DOM 元素。我 运行 遇到了我尝试创建按钮的问题,而 onClick 导致了问题。我得到 "TypeError: Cannot read property 'getIngredients' of undefined" 其中 getIngredients 是我试图调用的函数...

我尝试了什么:在它不起作用之前,我修复了一个绑定问题(使用箭头功能)。这允许页面动态创建元素。现在我的问题是 运行:单击按钮会引发错误。

构造函数

class Prediction extends React.Component {
  constructor(props) {
    super(props);
    this.state = { usersFood: "", domElementsObj: [], foodTemp: [] };
  }

获取配料函数

  getIngredients = params => {

    params.map(function(x, i) {
      console.log(i);
      fetch(
        `${base}?q=${params[0]}&app_id=${YOUR_APP_ID}&app_key=${YOUR_APP_KEY}`
      )
        .then(response => {
          console.log(response.json());
        })
        .catch(function(error) {
          console.log(error);
        });
    });
  };

动态创建 dom:

    let predictionDOM = this.state.domElementsObj.map(function(obj, i) {
      return (
        <div>
          <li key={obj[0]}>
            <button onClick={() => this.getIngredients(obj[0])}>
              {obj[0] + " -----"}
            </button>
            <span> ---- % of accuracy : {obj[1]} --</span>
            <button> Save to favorites</button>
          </li>
        </div>
      );
    });
    return (
      <div>
        <h1>testing api</h1>
        <p>Enter in your food :</p>
        <input
          type="text"
          value={this.state.usersFood}
          onChange={this.handleChange}
          placeholder="Enter your food"
        />
        <button onClick={this.getPredictions}>Make Predictions</button>
        {predictionDOM}
      </div>
    );
  }
}```


"You need to use arrow functions to preserve the context of this. So change it to let predictionDOM = this.state.domElementsObj.map((obj, i) => {... "

感谢@Jayce444 的帮助