【问题标题】:TypeError: cannot read property setState of undefinedTypeError:无法读取未定义的属性 setState
【发布时间】:2017-05-30 21:27:18
【问题描述】:

我正在从服务器接收数据,但无法在浏览器上显示。我收到错误:

捕获(承诺)类型错误:无法读取未定义的属性“setState”

import React from 'react';

import axios from 'axios';
class App extends React.Component {
constructor(props){
    super(props);
    this.state={
    posts:'hello',
    dos:[]
    }

};


    componentDidMount() {
    axios.get(`http://192.168.1.9:8082`)
      .then(function(data) {
      console.log(data);
      this.setState({dos:data});
      });
  }

   render() {
      return (
         <div>
            Hello World!!!
            <h1>{this.state.posts}</h1>
            <h2>{this.state.dos}</h2>
         </div>
      );
   }
}

export default App;

【问题讨论】:

  • 尝试 this.setState({dos:[data]}) 并在渲染中尝试

    {this.state.dos[0]}

  • console.log(data) 正确打印数据??
  • 在 console.log(data) 中打印正常
  • @vikas 我得到同样的错误 setState not undefined
  • 构造函数正确,无需更改。

标签: reactjs


【解决方案1】:

这是一个上下文问题,你的错误是你没有一直绑定到匿名函数。您可能想要做的是使用箭头函数,试试这个:

componentDidMount() {
   axios.get(`http://192.168.1.9:8082`)
    .then(data => this.setState({dos:data}););
}

箭头函数始终保持 this 的上下文。

替代解决方案:

componentDidMount() {
    axios.get(`http://192.168.1.9:8082`)
      .then(function(data) {
         console.log(data);
         this.setState({dos:data});
      }).bind(this);
}

【讨论】:

  • @ mayamk 它显示错误“对象作为 React 子项无效(找到:对象与键 {data, status, statusText, headers, config, request})。如果您打算渲染子集合,使用数组代替或使用 React 附加组件中的 createFragment(object) 包装对象。"
  • 发生这种情况是因为您在这一行&lt;h2&gt;{this.state.dos}&lt;/h2&gt; 中直接渲染html 中的对象,将其替换为特定属性,例如:&lt;h2&gt;{this.state.dos.data}&lt;/h2&gt;
  • 你不能直接在html中渲染整个对象,你必须给你特定的属性,让a={a:1,b:2}来渲染这个你必须使用&lt;div&gt;{a.a} , {a.b}&lt;/div&gt;
  • 你在状态中存储的数据包含这些键data, status, statusText, headers, config, request
【解决方案2】:

试试这个:

componentDidMount() {
    let self = this;
    axios.get(`http://192.168.1.9:8082`)
      .then(function(data) {
      console.log(data);
      self.setState({dos:data});
      });
  }

【讨论】:

    猜你喜欢
    • 2017-10-30
    • 2021-12-09
    • 2020-07-10
    • 2019-10-10
    • 2021-07-24
    • 2022-11-17
    • 2020-09-07
    相关资源
    最近更新 更多