Javascript 无法访问函数内部的状态
我正在为我的应用程序使用Javascript 无法访问函数内部的状态,javascript,reactjs,react-native,expo,Javascript,Reactjs,React Native,Expo,我正在为我的应用程序使用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
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>
);
}
}
import-React,
{Component}
从"反应",;
导入{
...
}从“反应本机”;
导出默认类App扩展React.Component{
状态={
傅:“ABC”,
酒吧:{
“ABC”:[
'...',
'...',
'...'
]
}
};
render(){
函数txt(n){
返回this.state.bar[this.state.foo][n];
}
返回(
...
);
}
}
我尝试将text()
函数放置在App
类之外,但得到了相同的错误
当我把它放在App
中的render()
之外时,我得到了一个意外的标记
错误
当我在
构造函数(props)
中定义此.state
并将text()
放置在构造函数
中时,我得到了引用错误:找不到变量:text
这里有一些问题。首先,需要将text
函数绑定到构造函数中的类。您还需要将text
函数移出呈现方法,并将其作为类方法添加(函数名称前面没有函数
):
import-React,
{Component}
从"反应",;
进口{
...
}从“反应本机”;
导出默认类App扩展React.Component{
构造函数(){
超级();
此.state={
傅:“ABC”,
酒吧:{
“ABC”:[
'...',
'...',
'...'
]
}
};
this.text=this.text.bind(this);
}
文本(n){
返回this.state.bar[this.state.foo][n];
}
render(){
返回(
...
);
}
}
您的问题是范围界定
您试图在txt()
函数中访问的this
指向它自己的this
,而不是外部组件this
有几种方法可以解决这个问题。以下是一些:
使用箭头函数
您可以将txt
转换为箭头函数,以使用外部此
:
render() {
const txt = (n) => {
return this.state.bar[this.state.foo][n];
}
return (
<View>
...
</View>
);
}
您可以创建一个指向外部this
render(){
const self=这个;
函数txt(n){
返回self.state.bar[self.state.foo][n];
}
返回(
...
);
}
其他办法
- 您可以将
函数移动到渲染函数的外部,并将其绑定到组件txt
this
- 您可以在component类块中使用箭头函数,这看起来像是将它绑定到组件的
this
- 可以将状态作为参数传递给函数
…我相信还有其他几种方法可以纠正这种行为。您只需要知道何时使用组件的
this
或其他this
使用数组-function@Thomas我相信你的意思是箭头函数
?Gives找不到变量:text
@MrigankPawagi使用Chase的答案,您需要在render
函数中使用this.text
,因为该函数在render
函数中不能作为关键字使用。您可以在渲染函数的顶部执行const text=this.text
,并从那时起在不使用this
的情况下使用它。非常感谢!工作得很有魅力!我使用了第二种方法,添加了consttext=\u text.bind(this)
,效果很好!基本上,我知道我必须使用bind()!像这样绑定它的“问题”是(甚至在渲染函数中创建函数)每次渲染组件时都要创建一个新的函数元素。这就是不在渲染函数中为非常大的组件创建函数的原因之一。我明白你的观点-谢天谢地,我的函数很小!谢谢
render() {
const txt = (n) => {
return this.state.bar[this.state.foo][n];
}
return (
<View>
...
</View>
);
}
render() {
function _txt(n){
return this.state.bar[this.state.foo][n];
}
const txt = _txt.bind(this);
return (
<View>
...
</View>
);
}
render() {
const self = this;
function txt(n){
return self.state.bar[self.state.foo][n];
}
return (
<View>
...
</View>
);
}