我有一个 React Native 组件,它需要从异步存储中获取一个对象才能进行渲染。像这样的东西。
class Class1 extends Component {
async render() {
let data = AsyncStorage.getItem('data');
return (
<View>
{data}
</View>
)
}
}
我让我的 render() 方法成为异步函数的原因是我可以等待 AsyncStorage.getItem() 方法的返回,以便组件不会尝试返回直到“数据”对象有已从异步存储返回。但是,当我使用“async render()”时,我得到“Invariant Violation: Objects are not valid as a React child”。
有小费吗?
最佳答案
不需要,您需要条件渲染这样的东西。
_retrieveData = async () => {
try {
const value = await AsyncStorage.getItem('data');
if (value !== null) {
// We have data!!
return (
<View>{value}</View>
);
}
} catch (error) {
// Error retrieving data
}
};
然后在您的渲染函数中,调用它。
render() {
return (
{this._retrieveData()}
)
}
关于react-native - 你可以在 React Native 异步中创建 render() 方法吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54539887/