我有一个Parent
组件和一个Child
组件,我的操作可以在子组件中触发一些api调用,而在componentWillMount
上,我签入了if
条件--一些来自父级的props
,并执行了一些触发器。如果条件为true,则触发呈现新组件的方法。问题是,在componentWillmount
中的子组件中,props
this.props.person
和this.props.notFound
是未定义的,但是在呈现和检查这个支持之前,我需要等待api请求。
父母:
export class Parent extends Component {
state = {
id: this.props.id || ''
}
render() {
<Child value={this.state.value} onNotValidId={() => this.renderNewComponent()} />
}
}
export const mapStateToProps = state => ({
tagStatus: state.tagAssignment.status,
persons: state.entities.persons,
)}
儿童:
export class Child extends Component {
componentWillMount = () => {
this.props.init(parseInt(this.props.id, 16), this.props.accessToken)
if (!this.props.notFound && !this.props.person)
this.props.onNotValidId()
}
render = () => {
return (
<div>Some body</div>
)
}
}
export const mapStateToProps = state => ({
status: state.tagAssignment.status,
person: state.entities.persons[state.tagAssignment.assignee],
accessToken: state.auth.accessToken,
})
export const mapDispatchToProps = dispatch => ({
init: (id, accessToken) => dispatch(checkId(id, accessToken)),
})
export default compose(
connect(mapStateToProps, mapDispatchToProps),
)(Child)
发布于 2018-05-11 13:20:02
您所遇到的问题正在发生,因为您对API的调用发生了asynchronously对react生命周期方法的调用。当API响应返回时,第一次调用父组件的呈现方法,从而呈现子组件,然后调用该组件,该子组件将与父组件在使用API响应数据初始化之前传递给它的支持一起挂载。当API结果最终被返回并作为新的支持传递到子组件(父组件重新呈现的结果)时,它将不会触发componentWillMount生命周期,因为它已经挂载了。
您可以通过多种方式解决这一问题,这取决于您今后计划如何使用子组件。有几个解决办法:
1)在父组件中,在返回API的响应之前,请确保不呈现子组件。这将确保当子组件第一次挂载时,它将有可使用的有效道具。例:
render() {
this.state.value && <Child value={this.state.value} onNotValidId={() => this.renderNewComponent()} />
}
2)将子组件初始化逻辑从/到另一个生命周期挂钩(如componentDidUpdate或getDerivedStateFromProps )移动或复制(取决于您对子组件的计划)(取决于您正在唱的React版本)。
https://stackoverflow.com/questions/50292600
复制相似问题