简体   繁体   English

我有一个this.state,我需要通过setState传入我的componentDidMount,如何在setState中使用bind(this)?

[英]I have one this.state and i need pass in my componentDidMount with setState, how use bind(this) in setState?

I have that pass Bind in setState, how to do? 我已经通过setState绑定了,怎么办? enter image description here 在此处输入图片说明

TypeError: Cannot read property 'setState' of undefined TypeError:无法读取未定义的属性“ setState”

I am using the RealTime Firebase and ReactJs 我正在使用RealTime Firebase和ReactJs

constructor() {
    super()
    this.app = firebase.initializeApp(firebase_config);
    this.database = this.app.database().ref().child('users');
    this.state = {
        users: []
    }
}
componentDidMount() {
  this.database.once("value", function(snapshot) {
      snapshot.forEach(function(data) {
          this.setState({users: data.val()})
      })
  });
}

render() {
   return (
    <BrowserRouter>
       <div className="App">
          <Navbar/>
          <Switch>
            <Route exact="exact" path='/' component={CampaingListClients}/>
          </Switch>
          <p>{this.state.users}</p>
       </div>
    </BrowserRouter>);
    }
}

TypeError: Cannot read property 'setState' of undefined TypeError:无法读取未定义的属性“ setState”

You can resolve setState undefined issue in two ways 您可以通过两种方式解决setState未定义问题

  1. Change your functions to arrow functions 将您的功能更改为箭头功能

     componentDidMount() { this.database.once("value", snapshot => { snapshot.forEach(data => { this.setState({users: data.val()}) }) }); } 
  2. Bind each function like below 如下绑定每个功能

      componentDidMount() { this.database.once("value", function(snapshot) { snapshot.forEach(function(data) { this.setState({users: data.val()}) }.bind(this)} }.bind(this)); } 

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 调用this.setState()时是否需要“…this.state” - Do I need “…this.state” when calling this.setState() 在渲染器中设置状态后,我需要在componentDidMount中更新一个api - I need to update an api inside a componentDidMount after I setState in a render 防止this.state与setState一起使用 - Prevent this.state to be used with setState setState ReactJS 中的 this.state - this.state inside setState ReactJS 当使用ComponentDidMount()时,我发现此错误:无法调用setState - When use ComponentDidMount() I found this error : Can't call setState 我如何在this.state中使用this.state - How can I use this.state within this.state 如何通过 setState 一键更改 state 值 - how can i change the state value with setState with one click reactjs、setState、Interface props 和 Interface state 之间的关系相对于 typescript,如何使用 setState? - relation between reactjs ,setState, Interface props and Interface state with respect to typescript , how can I use setState? 为什么我需要使用setState回调来设置依赖于第一个项目的setState整理的第二个状态项的状态? - Why do I need to use setState callback to set state for second state item that relies on first item's setState finishing? 我该如何外包使用state的函数并执行setState - How can i outsource functions that use state and do setState
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM