【问题标题】:What is the correct way to use AsyncStorage to update state in React-Native?在 React-Native 中使用 AsyncStorage 更新状态的正确方法是什么?
【发布时间】: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 的新手,所以也许我的想法是错误的。有人可以解释这样做的正确方法或建议替代方法吗?

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

【问题讨论】:

    标签: react-native asyncstorage


    【解决方案1】:

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

    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
    }
    

    【讨论】:

    • 谢谢!我刚刚更改了 setProductList(json_data) { this.setState({ products: json_data }) AsyncStorage.setItem('products': json_data); } 并且成功了!
    猜你喜欢
    • 2018-10-18
    • 1970-01-01
    • 2020-11-11
    • 2020-01-20
    • 1970-01-01
    • 2019-09-30
    • 1970-01-01
    • 2017-08-17
    • 1970-01-01
    相关资源
    最近更新 更多