简体   繁体   中英

How do you render a component based on an AsyncStorage value in React Native?

I have a component that looks like this:

export default class Class1 extends Component {
  render = async () => {
    await AsyncStorage.getItem('someValue', (error, someValue) => {
      return(
        <Class2 prop1={someValue}/>
      )
    }
  }
}

What's happening here is that I need to render Class1 based on the value of someValue that is returned from AsyncStorage. The problem is, you can't make the render() method async because async functions return a promise, and render() needs to return a React component.

Does anyone know how I can do this?

Thanks!

For this kind of tasks, you would put the value in your state. And based on the state, you will render the class as required.

In your componentDidMount of Class1, write:

componentDidMount() {
    AsyncStorage.getItem('value').then((val) => {
        this.setState({ value: val });
    })
}

Then in your Class1 add a method which will generate the class based on state value:

createClass() {
    // do something with the value
    if (this.state.value === somevalue) {
        return (
            <Class2 />
        )
    }
    return null;
}

And in your render method of Class1, type:

render() {
    return (
        { this.createClass() }
    )
}

You can set it to state, for example:

componentDidMount() {
  AsyncStorage.getItem('someValue', (e, someValue) => {
    this.setState({someValue})
  }
}

Then you can use someValue from state in your render.

Currently, in addition to the async render issue, since you're already passing in a callback to AsyncStorage.getItem(), I'm not sure what using async/await would do.

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