[英]Cannot access State inside Function
我正在为我的应用程序使用React Native
,有一次,我注意到我必须每次在我的组件中输入this.state.bar[this.state.foo][SOME_NUMBER]
。
这非常好用,但我想通过调用函数来使代码更清晰。 所以,我构建了这个:
function txt(n){
return this.state.bar[this.state.foo][n];
}
但是,当我在Expo
客户端中运行它时,我收到以下错误:
TypeError: undefined is not an object (evaluating 'this.state.bar')
This error is located at:
in App...
....
这是我的整个代码。
import React,
{ Component }
from 'react';
import {
...
} from 'react-native';
export default class App extends React.Component {
state = {
foo: 'ABC',
bar: {
'ABC': [
'...',
'...',
'...'
]
}
};
render() {
function txt(n){
return this.state.bar[this.state.foo][n];
}
return (
<View>
...
</View>
);
}
}
我尝试将text()
函数放在App
类之外,但是得到了同样的错误。
当我将它放在App
render()
外面时,我收到了unexpected token
错误。
当我定义this.state
一个内部constructor(props)
和放置text()
的内部constructor
,我得到ReferenceError: Can't find variable: text
你的问题是范围。
在this
,你试图向里面访问txt()
函数是指向自己的this
,而不是外部组件this
。
有几种方法可以解决这个问题。 这里有几个:
您可以将txt
成箭头功能使用外this
:
render() {
const txt = (n) => {
return this.state.bar[this.state.foo][n];
}
return (
<View>
...
</View>
);
}
this
render() {
function _txt(n){
return this.state.bar[this.state.foo][n];
}
const txt = _txt.bind(this);
return (
<View>
...
</View>
);
}
this
render() {
const self = this;
function txt(n){
return self.state.bar[self.state.foo][n];
}
return (
<View>
...
</View>
);
}
txt
函数移动到render函数之外,并将其绑定this
组件。 this
。 ...而且我确信还有其他几种方法可以解决这种问题。 你只需要当你使用组件的知道this
或其他一些this
。
这里有几个问题。 首先,您需要将text
函数绑定到构造函数中的类。 您还需要将text
函数移出render方法并将其作为类方法添加(函数名前面没有function
):
import React,
{ Component }
from 'react';
import {
...
} from 'react-native';
export default class App extends React.Component {
constructor () {
super();
this.state = {
foo: 'ABC',
bar: {
'ABC': [
'...',
'...',
'...'
]
}
};
this.text = this.text.bind(this);
}
text (n) {
return this.state.bar[this.state.foo][n];
}
render() {
return (
<View>
...
</View>
);
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.