反应错误 - 无法读取未定义的属性'setState'



下面的代码为我返回错误 未捕获(在承诺中(类型错误:无法读取未定义的属性"setState">

我是新手反应,这似乎很基本。任何建议我可能做错了什么。从 json 结果中,我想将所有名称存储在我的数组中。

import React, { Component } from "react";
class Search extends Component {
constructor(props) {
super(props);
this.state = {
list: [],
}
}
Search() {
fetch("http://url/getSearchResults")
.then(res => res.json())
.then(
(res) => {
this.setState({
list: res.data.name
})
})
}

这是 React 中类的一个非常常见的问题 - 有两种方法可以解决这个问题:

  1. 在构造函数中绑定方法:
constructor(props) {
super(props);
this.state = {
list: [],
}
this.Search = this.Search.bind(this);
}
  1. 改用箭头函数:
search = () => { ... }

有关更多信息,请参阅此帖子。

注意:如果您尝试在挂载时进行获取调用,则使用componentDidMount()将很有用 - 上面的答案解决了根据您看到的错误未定义this的问题。

componentDidMount()添加到Search(),它在组件挂载(插入树中(后立即调用。需要 DOM 节点的初始化应该转到此处。它是从远程端点加载数据的好地方。

最新更新