简体   繁体   中英

cant show updated state (REACT-NATIVE)

I want to show updated state name in the sidedrawer of my app,my functions work fine as I can see the name PRINTED twice in the console but for some reason I cannot show the name value on the app screen(shows starting value ""),I am thinking i might be using the wrong lifecycle method can someone help me?

state = {
    name: {
        value: ""
    }

componentWillMount() {

getTokens((value) => {
        if (value[0][1] === null) {
            alert('whoops')
        } else {
            this.props.UpdateUserData(value[0][1]).then(()=>{
                console.log(this.props.User.userData)
            this.state.name.value = this.props.User.userData
            console.log(this.state.name.value)
            })
}
    })
}
 render() {
    return (

        <View style={styles.container}>
                <Text style={styles.displayname}>{this.state.name.value} 
                 </Text>
        </View>
    )
}

this.state.name.value = this.props.User.userData

不要直接改变您的状态,因为它不会重新渲染组件,而是使用setState方法,如下所示

this.setState({ name: this.props.User.userData });

A quote from react-bits

Avoid async initialization in componentWillMount()

componentWillMount() is invoked immediately before mounting occurs. It is called before render(), therefore setting state in this method will not trigger a re-render. Avoid introducing any side-effects or subscriptions in this method.

Replace componentWillMount with componentDidMount . Should work

You are using this.state.name.value which is not correct. It sets the state but doesn't actually cause the component to re-render itself. Instead, you need to use the setState method to change the value of a state. This will make a call to re-render the component after the state has been changed. The example of that approach would be

this.setState({ name: this.propos.User.userData });

Although this approach works but it's not advised to mutate the value of state. States need to be considered immutable according to the guidelines.

componentWillMount does not differ much from constructor - it is also called once only in the initial mounting life-cycle. Many will be tempted to use this function in order to send a request to fetch data and expect the data to be available before the initial render is ready. This is not the case — while the request will be initialized before the render, it will not be able to finish before the render is called.

this.setState can solve the issue in this case.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM