【问题标题】:trying to set new state with function in componentDidMount: this.setState is not a function尝试使用 componentDidMount 中的函数设置新状态:this.setState 不是函数
【发布时间】:2016-06-03 02:18:30
【问题描述】:

我有一个名为 fetchUserssetTimout 函数,它会在 5 秒后返回用户。我试图在 componentDidMount 中调用 fetchUsers 来更新用户状态。我得到的错误是 this.setState 不是函数。如何正确更新componentDidMount函数中的用户状态?

var App = React.createClass({

  fetchUsers: function(cb){
    setTimeout(function(){
       cb([{name: 'joe'}, {name: 'john'}, {name: 'jim'}])
    }, 1000)
  },

  getInitialState: function(){
    return {
      users: [],
      loaded: false,
    }
  },

  componentDidMount: function(){
    this.fetchUsers(function(users){
      console.log(users);
      this.setState({
        users: users,
        loaded: true
      })
    })
  },

  render: function(){
    if(!this.state.loaded){
      return (
        <div>
          <p> Loading.... </p>
        </div>
        )
    };
    var users = this.state.data.map(function(user){
        return <li> {user.name} </li>
    });

    return(
        <div>
          <h3> Look at my users.. </h3>
          <ul> {users} </ul>
        </div>
      )
  }

})

React.render(<App/>, document.getElementById('hello'))

【问题讨论】:

    标签: reactjs components state


    【解决方案1】:

    您对此的引用有所不同。以下应该有效:

    componentDidMount: function(){
        this.fetchUsers(function(users){
          console.log(users);
          this.setState({
            users: users,
            loaded: true
          })
        }.bind(this))
    }
    

    【讨论】:

      猜你喜欢
      • 2017-05-04
      • 2019-04-21
      • 1970-01-01
      • 1970-01-01
      • 2018-11-27
      • 2019-03-21
      • 1970-01-01
      • 1970-01-01
      • 2016-10-27
      相关资源
      最近更新 更多