【问题标题】:componentWillMount check on undefined before api request will resolve在 api 请求解决之前,componentWillMount 检查未定义
【发布时间】:2018-05-11 08:19:49
【问题描述】:
我有一个组件可以触发一些依赖异步 API 请求的方法。我使用 componentWillmount 检查一些道具。如果这个道具是true,我会触发一些功能,否则为假。但问题是,第一次的 prop 是 undefined,只有一段时间后才会变成 false 或 true。如何检查并等待请求解决?
componentWillMount = () => {
this.props.init(parseInt(this.props.tagId, 16), this.props.accessToken);
if (!this.props.notFound && !this.props.person) this.props.onFreeTag();
};
【问题讨论】:
标签:
javascript
reactjs
ecmascript-6
react-lifecycle
【解决方案1】:
使用componentWillReceiveProps生命周期函数,类似:
componentWillReceiveProps = (nextProps) => {
if (!nextProps.notFound && !nextProps.person)
nextProps.onFreeTag()
}
}
【解决方案2】:
看起来,当组件第一次加载或被调用时,您正在向它传递一些最初未定义的值,后来变得可用。例如,假设您有一个父组件,如下所示
class Parent extends React.Component {
constructor() {
this.state = {0}
}
render() {
<Child value={this.state.value} />
}
}
如您所见,最初状态没有属性value,因此Child 将收到undefined 的this.props.value。当某些父函数像这样更改它时,它只会收到不undefined,
class Parent extends React.Component {
constructor() {
this.state = {0}
}
onAction() {
this.setState({value: true})
}
render() {
<Child value={this.state.value} />
}
}
因此,如果在某些事件上,父级调用其OnAction,它将改变状态,而子级将获得this.props.value 为true,但由于子级已经被渲染,componentWillMount 钩子不会被触发,但componentWillReceiveProps 会.因此,如果您想在componentWillMount 中使用道具,请确保它在孩子的第一次渲染时通过,如果不可能,请使用componentWillReceiveProps 来处理道具