1

我有一个Parent组件和Child一个组件,并且我有触发子组件中的一些 api 调用的操作,并且componentWillMount我检查了if一些props来自父组件并执行一些触发器的条件。如果条件为真,我会触发一个渲染新组件的方法。问题是在子组件中componentWillmountprops 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)
4

1 回答 1

1

您遇到的问题正在发生,因为您对 API 的调用与反应生命周期方法异步发生。当 API 响应返回时,父组件的 render 方法第一次被调用,该方法渲染了子组件,而子组件又调用该组件将在使用 API 响应初始化它们之前使用父传递给它的 props 进行挂载数据。当 API 结果最终返回并作为新的 props 传递给子组件时(父组件重新渲染的结果),它不会触发 componentWillMount 生命周期,因为它已经挂载。

您可以通过多种方式解决此问题,这实际上取决于您计划将来如何使用子组件。几个解决方案:

1) 在您的父组件渲染方法中,确保在返回 API 的响应之前不渲染子组件。这将确保当子组件第一次挂载时,它将有有效的道具可以使用。例如:

render() {
  this.state.value && <Child value={this.state.value} onNotValidId={() => this.renderNewComponent()} />
}

2)移动或复制(取决于您对子组件的计划)子组件初始化逻辑从/到另一个生命周期钩子,例如 componentDidUpdate 或 getDerivedStateFromProps (取决于您正在使用的 React 版本)

于 2018-05-11T13:20:02.787 回答