【问题标题】:React - State return undefined反应 - 状态返回未定义
【发布时间】:2020-08-20 22:53:00
【问题描述】:

我在课堂上使用状态变量,但它似乎不起作用。当我尝试通过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】:

    有两个问题:

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

    console.log(this.state.searchMode)
    

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

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-07-19
      • 2019-12-13
      • 1970-01-01
      • 2022-12-16
      • 1970-01-01
      相关资源
      最近更新 更多