【发布时间】:2020-06-17 08:36:47
【问题描述】:
我在 props 中有承诺:this.props.getProfile(),我想在 render() 之前将 promise 中的响应值设置为状态
我尝试过使用UNSAFE_componentWillMount 和getDerivedStateFromProps,但它总是响应未决的承诺。
这是我对UNSAFE_componentWillMount的尝试:
UNSAFE_componentWillMount(){
this.setState({profile: this.getProfile()})
}
getProfile=()=>{
return this.props.getProfile()
.then(res =>{
if (res.type === 'ERROR_MESSAGE') {
return null;
}
return res.payload
});
}
这是我对getDerivedStateFromProps的尝试:
static getDerivedStateFromProps (props, state){
let a = props.getProfile()
.then(res =>{
if (res.type === 'ERROR_MESSAGE') {
return null;
}
return res.payload
});
console.log(a);
if(a.profile !== state.profile)
return {profile: a};
}
【问题讨论】:
-
在渲染组件之前解决promise,而不是在组件内执行。这样你就不用提供 Promise 作为道具,而是准备好渲染的最终值。
-
怎么办,我的props只是一个axios请求,不是组件