javascript - 无法访问函数内部的状态
问题描述
我正在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
课堂之外,但得到了同样的错误。
当我把它放在外面render()
时App
,我得到了一个unexpected token
错误。
当我this.state
在 a中定义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
函数移动到渲染函数之外并将其绑定到组件this
。 - 您可以在组件类块内使用箭头函数,这看起来就像您已将其绑定到组件的
this
. - 您可以将状态作为参数传递给函数
...而且我确信还有其他几种方法可以解决此问题。您只需要知道何时使用组件this
或其他this
.
推荐阅读
- flutter - 如何在 Flutter App 的文本框右侧添加美元符号
- amazon-web-services - 使用 QoS.EXACTLY_ONCE 订阅主题时使用 awsiotsdk,遇到 AWS_ERROR_MQTT_UNEXPECTED_HANGUP
- javascript - 如何检查是否使用 Jasmine 中的特定选择器调用了 jQuery、$?
- curl - 在 WSO2 API 管理器中使用 POST 请求时出现错误 411
- wordpress - WP_Query 传递一个唯一标识符以用于稍后的操作挂钩?
- python - 代码@discord bot 并让它回复你的前缀和等等等等
- material-design - Snowpack + Svelte + svelte-materialify 缺少图标
- python - 使用 pd.pivot 在 Python 中进行透视
- cassandra - 如何使用列中的 JSON 子对象从 Cassandra 中进行选择?
- sql - 没有预期的关键字 IF