简体   繁体   中英

update state with AsyncStorage - React Native

I have a small problem with componentWillMount when I want to update the component's state I get this error.

在此处输入图片说明

the code is this :

export default class RouterComponent extends Component {

constructor(props) {
    super(props);
    this.state = {
        isLogin: null
    }
}

componentWillMount = async () => {
    AsyncStorage.getItem('@MyUserFireBase:key').then(response => {
        this.setState({ 'isLogin': true });
    }).done();
}



render() {

    return (
        <Router>
            <Stack key="root" hideNavBar>
                <Stack key="main">
                    <Scene key="login" initial={!this.state.isLogin} component={LoginForm} title="Login" />
                    <Scene key="employeeList" initial={this.state.isLogin} component={EmployeeList} title="Employee List" />
                </Stack>
            </Stack>
        </Router >
    )
}

}

I have more than 3 days looking for the solution and I can not find it. What am I doing wrong? Thanks for your time

Check out component lifecycle methods to help you with your problem: https://engineering.musefind.com/react-lifecycle-methods-how-and-when-to-use-them-2111a1b692b1

For my answer, try this:

componentDidMount = async () => {
    AsyncStorage.getItem('@MyUserFireBase:key').then(response => {
        this.setState({ 'isLogin': true });
    }).done();
}

Also, if that does not work, try Update instead, since you are setting the state:

componentDidUpdate() =  {
        AsyncStorage.getItem('@MyUserFireBase:key').then(response => {
            this.setState({ 'isLogin': true });
        }).done();
    }

Use componentDidMount() instead of componentWillMount() and remove async()

componentDidMount() {
    AsyncStorage.getItem('@MyUserFireBase:key').then(response => {
        this.setState({ 'isLogin': true });
    }).done();
}

componentWillMount is also marked as deprecated in React 16.3 https://reactjs.org/blog/2018/03/29/react-v-16-3.html (Lifecycle section)

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