React - 状态返回未定义

问题描述 投票:-1回答:1

我在我的类中使用了状态变量,但似乎没有用。当我试图通过 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>
        )
    }
}
reactjs react-native state react-state-management
1个回答
3
投票

有两个问题。

你的 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))
}}
© www.soinside.com 2019 - 2024. All rights reserved.