javascript - react-native - 当获取结束时调用另一个函数

标签 javascript asynchronous react-native request fetch

我是 React-Native 新手

我有fetch,通过它我获取了一些数据。我想做的是在请求结束并且数据准备好后调用另一个函数或更新状态。这是我的代码。

getProducts()
    {
        return fetch(prodUrl, {method: "GET"})
            .then((response) => response.json())
            .then((responseData) => {
                this.setState({brandList: responseData.products});
                console.log("Brands State -> : ",this.state.brandList)
            })
            .done();
    }

我在 componentWillMount() 中调用此 getProducts() 函数,并尝试在 render() 中使用获取的数据。 设置状态后,当我尝试 console.log() 时,我看不到变化,很可能是因为 fetch() 是异步的。如何在 fetch() 结束之前停止执行 render() 函数?或者您可以推荐任何其他请求类型,而不是同步的 fetch()

最佳答案

这并不是因为 fetch 是异步的,此时您已经拥有了 responseData。这是因为 setState 不会立即更改状态,因此在更改状态之前会调用 console.log 。 setState 有一个可选的回调,因为它是第二个参数,一旦 set 更新完成,就会调用该回调,因此您可以像这样更改它以正确查看效果:

getProducts()
    {
        return fetch(prodUrl, {method: "GET"})
            .then((response) => response.json())
            .then((responseData) => {
                this.setState(
                  {brandList: responseData.products},
                  () => console.log("Brands State -> : ",this.state.brandList)
                );  
            });
    }

关于javascript - react-native - 当获取结束时调用另一个函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42484829/

相关文章:

javascript - 将 TD 列转换为 TR 行

javascript - 传单 map 并不总是加载居中的相同 WMS 平铺层

Javascript对象方法不更新变量

c# - 任务类无法获取正确的值

java - 将 ThreadLocal 与 CompletableFuture 一起使用安全吗?

react-native - 如何将边框半径应用于 Expo LinearGradient 组件的某些角

javascript - 将 Google 地理编码器的结果放入数组中?

node.js - 在 NodeJS 中使用异步响应进行异步调用

javascript - react native 键盘避免使用 native 基础的 View

javascript - 如何使用 Javascript fetch() 无需递归即可获取 REST 分页数据?