简体   繁体   English

react-native-提取结束后调用另一个函数

[英]react-native - call another function when fetch is over

I'm new to React-Native 我是React-Native的新手

I have fetch , through which I get some data. 我有fetch ,通过它我可以获取一些数据。 What I want to do is to call another function or update the state, after the request is over and data is ready. 我想要做的是在请求结束并且数据准备好之后,调用另一个函数或更新状态。 Here is my code. 这是我的代码。

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();
    }

I call this getProducts() function in componentWillMount() and trying to use fetched data in render() . 我在componentWillMount()将此方法称为getProducts()函数,并尝试在render()使用获取的数据。 After I set the state, I can't see the change when I try to console.log() , most probably because fetch() is async. 设置状态后,尝试console.log()时看不到更改,这很可能是因为fetch()是异步的。 How can I stop execution of render() function before fetch() is over? 如何在fetch()之前停止执行render()函数? Or can you recommend any other request type rather then fetch() which is sync. 或者您可以推荐其他任何请求类型,而不是同步的fetch()

It's not because fetch is async, you already have your responseData at that point. 不是因为fetch是异步的,那时候您已经具有了responseData。 It is because setState doesn't change state immediately, so you're console.log is being called before state is being changed. 这是因为setState不会立即更改状态,因此您在更改状态之前调用console.log。 setState has an optional callback as it's second parameter that will be called once set is done being updated, so you can change it like this to see the effect correctly: setState有一个可选的回调,因为它是第二个参数,一旦完成设置更新,将调用它,因此您可以像这样更改它以正确查看效果:

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

You do not want to "stop" the render() function from being executed. 您不想“停止” render()函数的执行。 You can, however, apply a check in render if the data is available and render a spinner or something else while it is not. 但是,您可以在数据可用的情况下应用检入渲染,并在微调器或其他数据不可用时进行渲染。

Very rough sketch of how this could look like: 关于它的外观非常粗略:

render() {
  let component = this.state.brandList ? <ComponentWithData/> : <Spinner/>;
  return component;
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM