【发布时间】:2019-09-10 10:44:52
【问题描述】:
我有这个简单的代码。
export default class ProductDetail extends Component {
constructor(props) {
super(props);
this.state = { test: null,id:this.props.navigation.state.params.productId };
console.log(1);
}
componentWillMount() {
console.log(2);
this.getProductRequest(this.state.id);
console.log(3);
}
async getProductRequest(id) {
try {
let api_token = await AsyncStorage.getItem('apiToken')
let response = await fetch('...')
let json = await response.json();
this.setState({test: json});
} catch(error) {
//
}
}
render() {
console.log(4);
console.log(this.state.test);
return (
<View><Text>test</Text></View>
);
}
}
现在,我在调试器中检查了它:
我期待这个结果:
1
2
3
4
{数据:{…},状态:“成功”,…}
但我明白了:
1
2
3
4
空
4
{数据:{…},状态:“成功”,…}
我认为这意味着 render() 运行两次!
我该如何处理这个错误?
【问题讨论】:
-
componentWillMount 已被弃用,特别是因为它经常被滥用。异步调用属于 componentDidMount。
标签: json reactjs react-native async-await