[英]How to access this.state from a function inside componentDidMount in React Native?
this.state
is undefined when I try to use it inside a function within componentDidMount
. 当我尝试在
componentDidMount
的函数内使用this.state
时,它是未定义的。 this
is referring to the component within componentDidMount
, but not when it is called from the nested function. this
是指componentDidMount中的componentDidMount
,但不是从嵌套函数中调用时。 I have tried binding this to to the function but have not had any luck. 我尝试将其绑定到函数,但没有任何运气。 I am using React Native, but I believe this applies to React in general.
我正在使用React Native,但我相信这通常适用于React。 Here is
componentDidMount
: 这是
componentDidMount
:
componentDidMount(){
console.log(this.state); //is state of the Component
//this.state.foos is an array
var foosRef = firebase.database().ref('foos');
foosRef.on('child_added', function(child){
console.log(this.state); //is undefined
this.setState((prevState) => {
return {foos: prevState.push(child) }
})
}).bind(this)
}
I currently have the following in my constructor: 我目前在构造函数中具有以下内容:
this.componentDidMount.bind(this);
I also tried binding this
at the end of the callback, instead of after .on
but that does not work either. 我也尝试结合
this
在回调结束,而不是之后.on
,但是,不能正常工作。
The error is: 错误是:
TypeError: prevState.push is not a function. (In 'prevState.push(child)', prevState.push is undefined)
state
is not a property of this
. state
不是一个属性this
。
I know you shouldn't mutate prevState
, but I was previously doing 我知道你不应该变异
prevState
,但是我以前在做
this.state.foos.push(child)
and haven't looked up the syntax for adding an element as a copy of the original. 并且没有查找将元素添加为原始副本的语法。
the problem is the context of 'this' within your handler function is not your component's definition. 问题是处理程序函数中“ this”的上下文不是组件的定义。 You can solve this in one of three ways:
您可以通过以下三种方式之一解决此问题:
before calling foosRef.on, add 在调用foosRef.on之前,添加
let my = this;
then reference "my" inside your inline handler function instead of "this". 然后在内联处理程序函数中引用“ my”,而不是“ this”。
OR, 2. move your inline handler function to a standalone member of your component class, eg: 或者,2.将内联处理程序函数移至组件类的独立成员,例如:
function foosRefOnHandler(child){
console.log(this.state); //is undefined
this.setState((prevState) => {
return {foos: prevState.push(child) }
}
then, you would have to change your foosRef.on call to bind that method: 然后,您将必须更改foosRef.on调用以绑定该方法:
foosRef.on('child_added', this.foosRefOnHandler.bind(this));
OR, 3. using an inline arrow function instead of handler, eg: 或3.使用内联箭头函数代替处理程序,例如:
foosRef.on('child_added', (child) => {
console.log(this.state); //is undefined
this.setState((prevState) => {
return {foos: prevState.push(child) }
})
})
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.