【发布时间】:2017-01-05 21:56:13
【问题描述】:
我正在尝试向服务器发出 GET 请求,以检索 JSON 格式的产品列表。然后我想将数据放入 AsyncStorage 中,以便在视图中显示产品。这样做的正确方法是什么?
我研究过的内容:
在 https://facebook.github.io/react-native/docs/asyncstorage.html 上,在示例中,他们解释了如何从 AsyncStorage 中检索一个值,而不是同时设置和检索它
我有什么:
componentDidMount () {
this.fetchProducts()
this._loadInitialState().done();
}
_loadInitialState = async () => {
try {
var value = await AsyncStorage.getItem('products')
if (value != null) {
this.setState({products: value});
}
} catch (error) {
console.log("error setting product list");
}
}
fetchProducts() {
fetch("http://localhost:3000/products",{
method: "GET",
headers: {
'Content-Type': 'application/json'
},
})
.then((response) => (response.json()))
.then((data) => setProductList(data));
}
setProductList(json_data) {
Async.setItem('products': json_data);
}
render() {
console.log(this.state.products)
//render view
}
-> this.state.products 为空,我确信服务器会通过 curl 返回响应。我是 react-native 的新手,所以也许我的想法是错误的。有人可以解释这样做的正确方法或建议替代方法吗?
我所知道的 异步存储是应用程序可以放置其数据的键值存储。这些数据可以从异步存储中放入对象的状态中,并且视图会相应地更新
【问题讨论】: