在 React-Native 中使用 AsyncStorage 更新状态的正确方法是什么?

What is the correct way to use AsyncStorage to update state in React-Native?

我正在尝试向服务器发出 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 为空,我确定服务器 returns 通过 curl 响应。我是 react-native 的新手,所以也许我的想法不对。有人可以解释执行此操作的正确方法或建议替代方法吗?

我所知道的 异步存储是应用程序可以放置其数据的键值存储。此数据可以从异步存储放入对象的状态,视图将相应更新

您可以在从提取请求中获取数据后将其设置为状态,而不是设置异步存储并从中获取:

componentDidMount () {
    this.fetchProducts()
}

fetchProducts() {
    fetch("http://localhost:3000/products",{
      method: "GET",
      headers: {
        'Content-Type': 'application/json'
      },
    })
    .then((response) => (response.json()))
    .then((data) => setProductList(data)); 

}

setProductList(json_data) {
    this.setState({ products: json_data }, () => {     //Here
      Async.setItem('products': json_data);
    }
}

render() {
    console.log(this.state.products) 
    //render view
}