sha*_*abi 5 javascript ecmascript-6 react-native
我的问题是我想从这个函数中得到一个 json 但我得到的只是一个承诺,为什么我选择这种方式是因为在我正在处理的应用程序中它是动态工作的,但我看到的唯一地方我可以把这个承诺是渲染()
这是我的代码:
var userInfo = (async()=>{
var value = await AsyncStorage.getItem("@user_info");
value = JSON.parse(value);
return value ;
})();
Run Code Online (Sandbox Code Playgroud)
这是我的结果:
Promise {
"_40": 0,
"_55": null,
"_65": 0,
"_72": null,
}
Run Code Online (Sandbox Code Playgroud)
但我想要的是一个 json 我必须做什么?
您必须componentDidMount在 Promise 完成后调用此函数,然后调用setState。
以下是如何执行此操作的规范示例:
class User extends React.Component {
state = { user: null };
render() {
return this.state.user && <div>{this.state.user.name}</div>;
}
async componentDidMount() {
const value = await AsyncStorage.getItem("@user_info");
if (!this._unmounted) {
const user = JSON.parse(value);
this.setState({ user: user });
}
}
componentWillUnmount() {
this._unmounted = true;
}
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
6872 次 |
| 最近记录: |