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

后端 未结 1 743
佛祖请我去吃肉
佛祖请我去吃肉 2021-01-07 08:18

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

相关标签:
1条回答
  • 2021-01-07 09:17

    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
    }
    
    0 讨论(0)
提交回复
热议问题