[英]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.