[英]React error - Cannot read property 'setState' of undefined
Below code returns an error for me Uncaught (in promise) TypeError: Cannot read property 'setState' of undefined下面的代码为我返回一个错误 Uncaught (in promise) TypeError: Cannot read property 'setState' of undefined
I am new to react and this seems very basic.我是新来的反应,这似乎非常基本。 Any suggestion what could I be doing wrong.
任何建议我可能做错了什么。 From the json result I want to store all names in my array.
从 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
})
})
}
This is a very common problem with classes in React - there are two ways to solve this problem:这是 React 中类的一个非常常见的问题——有两种方法可以解决这个问题:
constructor(props) {
super(props);
this.state = {
list: [],
}
this.Search = this.Search.bind(this);
}
search = () => { ... }
See this post for more information.有关更多信息,请参阅此帖子。
Note : using componentDidMount()
will be useful if you are trying to make the fetch call on mount - the answer above addresses the issue of this
being undefined as per the error you are seeing.注:使用
componentDidMount()
如果你正在努力让自己在安装取通话将是有益的-上面的地址问题的答案this
被未定义按照您所看到的错误。
Add componentDidMount()
to Search()
, it is invoked immediately after a component is mounted (inserted into the tree).将
componentDidMount()
添加到Search()
,在安装组件(插入到树中)后立即调用它。 Initialization that requires DOM nodes should go here.Its a good place to load data from a remote endpoint.需要 DOM 节点的初始化应该放在这里。它是从远程端点加载数据的好地方。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.