[英]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. 这里发生的事情是,我需要根据AsyncStorage返回的
someValue
的值来呈现Class1。 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. 问题是,您不能使
render()
方法异步,因为异步函数返回一个Promise,而render()
需要返回一个React组件。
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: 在Class1的componentDidMount中,编写:
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: 然后在Class1中添加一个方法,该方法将根据状态值生成类:
createClass() {
// do something with the value
if (this.state.value === somevalue) {
return (
<Class2 />
)
}
return null;
}
And in your render method of Class1, type: 在Class1的渲染方法中,键入:
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. 然后,您可以在渲染中使用state中的
someValue
。
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. 当前,除了异步渲染问题之外,由于您已经将回调传递给AsyncStorage.getItem(),因此我不确定使用async / await会做什么。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.