反应-状态返回未定义

时间:2020-05-06 04:21:35

标签: reactjs react-native state react-state-management

我在类上使用状态变量,但似乎不起作用。当我尝试通过console.log查看其值时,它将返回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>
        )
    }
}

1 个答案:

答案 0 :(得分:3)

有两个问题:

您在console.log中缺少“状态”。

console.log(this.state.searchMode)

但是,如果我们现在将其记录下来,您将获得过时的值this.state.searchMode。这是因为setState是异步的。但是,setState在第二个参数中接受一个回调,该回调将在setState完成后被调用,以便您可以记录新状态。将您的onPress更新为:

onPress={() => {
  this.setState({searchMode: true}, () => console.log(this.state.searchMode))
}}