React本机获取状态不更新
问题描述:
使用Fetch API对本机做出反应,这不会在完成承诺后更新ui。React本机获取状态不更新
当我们触摸屏幕(是的,并用正确的数据更新UI)时,我们意识到承诺的解决方案。
对于workarround,我们使用axios(https://github.com/mzabriskie/axios)并解决了我们的问题。
下面是代码:
产品service.js
export class ProductsService {
constructor() {
}
getProductDetail(id) {
let url = 'http://myservice/product-detail/' + id;
return fetch(url)
.then((response) => response.json());
}
}
我-component.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>
);
}
}
当我们使用抓取,产品名称才会显示我们触摸设备屏幕。 当我们使用axios时,它工作。
这是一个错误?
环境:Windows 10,安卓6,阵营本地0.31
答
我不使用
反应本地人,但是,刚才有同样的问题。这个东西是this.setState当诺言解决不指向组件。
之前抓取叫我存储这一个变种
const thiz = this;
,然后使用THIZ VAR设置状态
thiz.setState({});
,或者你可以在功能结合THIZ
then((function(){
this.setState({});
}).bind(thiz))
我认为这是RN获取错误。 – deju