【问题标题】:React - Cannot read property 'state' of undefinedReact - 无法读取未定义的属性“状态”
【发布时间】:2017-08-15 08:56:59
【问题描述】:

尽管在使用 setState 时使用胖箭头函数绑定 this 的上下文,但我仍然收到此错误。有人可以帮忙吗?

export default class App extends Component {

constructor(props) {
    super(props);
    this.state = {
        query: '',
        items: [],
        repos: []
    };
}

search(term) {
    this.setState({
        query: term
    });
    const clientId = '12489b7d9ed4251ebbca';
    const secret = 'ff53ac9a93aaa9e7cddc0c009d6f068302866ff2';

    function fetchUser() {
        return axios.get(`https://api.github.com/users/${this.state.query}/repos?client_id=${clientId}client_secret=${secret}`);
    }

    function fetchRepos() {
        return axios.get(`https://api.github.com/users/${this.state.query}?client_id=${clientId}client_secret=${secret}`);
    }

    axios.all([fetchUser(), fetchRepos()])
        .then(axios.spread((items, repos) => {
            this.setState({
                items: items.data,
                repos: repos.data

            });
            console.log(state);
        }));

}

【问题讨论】:

  • 你能看到发生错误的代码行吗?
  • fetchUser 失败。我只是添加了这个变量。常量查询 = this.state.query;谢谢修复!
  • 添加到我的答案中,您应该使用箭头函数,因为它们将重用父 this

标签: reactjs


【解决方案1】:

从错误消息中可以清楚地看出this 是未定义的。这可能是因为您在search() 中使用它,而search() 未绑定到组件,使this 完全没有意义。要解决此问题,请尝试在构造函数的末尾添加这一行:

        this.search = this.search.bind(this);

现在您应该可以在搜索功能中使用this

【讨论】:

    【解决方案2】:

    setState 不同步。如果想在设置后使用状态的值,则必须在对象后的 setState 内提供回调。

    我会这样做:

    onSearch(term) {
      this.setState({ query: term }, () => {
        console.log(this.state.query);
        this.search();
      });
    }
    
    search() {
      // now you can be sure, that this.state.query is set and use it.. 
    
      // Use arrow functions, as they will reuse the parent scope.
      const fetchUser = () => {
    
      }
    }
    

    【讨论】:

    • 我宁愿将该词作为参数传递给搜索函数,而不是等待回调。
    • 可能,如果 UI 中不需要该术语,您当然可以忘记它。另一方面,有时您希望使用相同的参数集(来自状态)再次执行查询,就像在 OP 中一样,在这种情况下,最好使用单个方法搜索,这将依赖于状态。更改查询参数时,我们首先应该更新状态,然后执行搜索。顺便说一句,我发现演示 setState + 回调很有用
    • 我正在考虑一些更复杂的带有标签/类别等的搜索表单。在 React 中,每个更改都会有另一个事件处理程序,例如 onTagsonCategoriesonSearchTerm。因此,在状态更新后,您仍然可以调用单个 search 方法。
    【解决方案3】:

    如果来自fetchUser 的错误,我认为您在search 函数中有正确的this。所以需要绑定fetchUserfetchRepos

    const fetchUser = () => {
            return axios.get(`https://api.github.com/users/${this.state.query}/repos?client_id=${clientId}client_secret=${secret}`);
        }
    

    或者

    const fetchUser = function(){
            return axios.get(`https://api.github.com/users/${this.state.query}/repos?client_id=${clientId}client_secret=${secret}`);
        }.bind(this);
    

    fetchRepos 也是如此。

    【讨论】:

    • @Dennis,这个答案有帮助吗?
    猜你喜欢
    • 1970-01-01
    • 2019-06-08
    • 2021-11-28
    • 2020-08-31
    • 2019-07-25
    • 2020-11-05
    • 2021-07-07
    相关资源
    最近更新 更多