反应 - 状态 return 未定义
React - State return undefined
我在 class 上使用状态变量,但它似乎不起作用。当我尝试通过 console.log
查看它的值时,它 returns undefined
。我做错了什么?
class ContactScreen extends Component {
static contextType = Context
constructor(props) {
super(props)
this.state = {
searchMode: false //this is my variable
}
setTimeout(() => {
StatusBar.setBackgroundColor(primary)
}, 100)
}
onContactAction = (contact) => {
this.props.navigation.navigate('Chat', {contact})
}
render() {
const { state } = this.context
const { contactList } = state
return (
<Container>
{ this.searchMode ? //validate variable value
<SearchHeader/> :
<Header style= {appStyles.headerBackgroundColor}>
...
<Right>
<Button
transparent
style={{marginRight:5}}
onPress={() => {
this.setState({searchMode: true}) //set variable value
console.log(this.searchMode)
}}>
<Icon type= 'Octicons' name= 'search'/>
</Button>
<PopupMenu type= 'main'/>
</Right>
</Header>
}
<ContactList onContactAction={(id) => this.onContactAction(id)}/>
</Container>
)
}
}
有两个问题:
您的 console.log 中缺少 'state'。
console.log(this.state.searchMode)
但是,如果我们现在记录它,您将得到一个过时的值 this.state.searchMode
。这是因为 setState 是异步的。但是,setState 接受第二个参数中的回调,该回调将在 setState 完成后调用,以便您可以记录新状态。将您的 onPress 更新为:
onPress={() => {
this.setState({searchMode: true}, () => console.log(this.state.searchMode))
}}
我在 class 上使用状态变量,但它似乎不起作用。当我尝试通过 console.log
查看它的值时,它 returns undefined
。我做错了什么?
class ContactScreen extends Component {
static contextType = Context
constructor(props) {
super(props)
this.state = {
searchMode: false //this is my variable
}
setTimeout(() => {
StatusBar.setBackgroundColor(primary)
}, 100)
}
onContactAction = (contact) => {
this.props.navigation.navigate('Chat', {contact})
}
render() {
const { state } = this.context
const { contactList } = state
return (
<Container>
{ this.searchMode ? //validate variable value
<SearchHeader/> :
<Header style= {appStyles.headerBackgroundColor}>
...
<Right>
<Button
transparent
style={{marginRight:5}}
onPress={() => {
this.setState({searchMode: true}) //set variable value
console.log(this.searchMode)
}}>
<Icon type= 'Octicons' name= 'search'/>
</Button>
<PopupMenu type= 'main'/>
</Right>
</Header>
}
<ContactList onContactAction={(id) => this.onContactAction(id)}/>
</Container>
)
}
}
有两个问题:
您的 console.log 中缺少 'state'。
console.log(this.state.searchMode)
但是,如果我们现在记录它,您将得到一个过时的值 this.state.searchMode
。这是因为 setState 是异步的。但是,setState 接受第二个参数中的回调,该回调将在 setState 完成后调用,以便您可以记录新状态。将您的 onPress 更新为:
onPress={() => {
this.setState({searchMode: true}, () => console.log(this.state.searchMode))
}}