【发布时间】: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