在 React-Native 中使用 AsyncStorage 更新状态的正确方法是什么? [英] What is the correct way to use AsyncStorage to update state in React-Native?

查看:73
本文介绍了在 React-Native 中使用 AsyncStorage 更新状态的正确方法是什么?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试向服务器发出 GET 请求,以检索 JSON 格式的产品列表.然后我想将数据放入 AsyncStorage 以便我可以在视图中显示产品.这样做的正确方法是什么?

I'm trying to make a GET request to a server to retrieve a list of products in JSON form. I then want to put the data into AsyncStorage so I can display the products in the view. What's the correct way to do this?

我的研究:

https://facebook.github.io/react-native/docs/asyncstorage.html ,在示例中,他们解释了如何从 AsyncStorage 检索值,而不是设置它并同时检索它

on https://facebook.github.io/react-native/docs/asyncstorage.html , in the example, they explain how to retrieve a value from AsyncStorage, not set it and retrieve it at the same time

我所拥有的:

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 返回响应.我是本机反应的新手,所以也许我的想法是错误的.有人可以解释执行此操作的正确方法或建议替代方法吗?

-> this.state.products is null and I know for sure the server returns a response through curl. I'm new to react-native so perhaps my thinking is off. Could someone explain the correct way to do this or suggest an alternative method?

我所知道的异步存储是一个键值存储,应用程序可以在其中放置其数据.这些数据可以从异步存储中放入对象的状态,视图会相应地更新

What I know Async storage is a key value store where an app can place its data. This data can be put from async storage into the object's state and the view will update accordingly

推荐答案

不是设置并从异步存储中获取,您只需在从 fetch 请求中获取数据后将其设置为 state:

Instead of setting and getting from async storage, you can just set it to state once you get the data from your fetch request:

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
}

这篇关于在 React-Native 中使用 AsyncStorage 更新状态的正确方法是什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆