【问题标题】:React Native fetch state not updateReact Native 获取状态不更新
【发布时间】:2016-08-24 14:43:29
【问题描述】:

在 react native 上使用 Fetch API,这不会在 promise 完成后更新 ui。

当我们触摸屏幕时,我们实现了 promise resolve(是的,并用正确的数据更新 ui)。

对于 workarround,我们使用 axios (https://github.com/mzabriskie/axios) 并解决了我们的问题。

代码如下:

product-service.js

export class ProductsService {
    constructor() {
    }

    getProductDetail(id) {
        let url = 'http://myservice/product-detail/' + id;
        return fetch(url)
            .then((response) => response.json());
    }
}

我的组件.js

export class MyComponent extends Component {
    constructor(props) {
        super(props);

        this.state = {
            product: {}
        };
    }

    componentDidMount() {
         let productService = new ProductsService();
         productService.getProductDetail(1)
            .then((productDetail) => {
                console.log('updateProduct: ', productDetail);
                this.setState({
                    product: productDetail
                });
            })
            .catch((error) => {
                console.error(error);
            });
    }

    render() {
        return (
            <View>
                <Text>{this.state.product.name}</Text>
            </View>
        );
    }
}

当我们使用 fetch 时,产品的名称只有在我们触摸设备屏幕时才会出现。 当我们使用 axios 时,它可以工作。

这是一个错误?

环境:Windows 10、Android 6、React Native 0.31

【问题讨论】:

  • 我认为是 RN fetch bug。

标签: react-native state fetch react-native-android


【解决方案1】:

我没有使用本机反应,但是刚才遇到了同样的问题。 this.setState 当 Promise 解析时不指向组件。

在 fetch 调用之前,我将 this 存储在 var 上

const thiz = this;

然后使用 thiz var 设置状态

thiz.setState({});

或者您可以将函数绑定到 thiz

then((function(){
    this.setState({});
}).bind(thiz))

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-12-25
    • 2020-09-06
    • 2020-04-24
    • 2022-01-22
    相关资源
    最近更新 更多