【发布时间】:2019-03-24 11:23:12
【问题描述】:
我在我的应用程序中使用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 错误。
当我在constructor(props) 中定义this.state 并将text() 放在constructor 中时,我得到了ReferenceError: Can't find variable: text
【问题讨论】:
-
使用数组函数
-
@Thomas 我相信你的意思是
arrow-function?
标签: javascript reactjs react-native expo