【问题标题】:React check api request before pass props to Children在将道具传递给儿童之前反应检查 api 请求
【发布时间】:2018-05-11 12:41:26
【问题描述】:

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

【问题讨论】:

  • 我可能会使用 componentDidUpdate 并设置一个变量状态,然后使用它仅在发生更新(例如来自 Api 调用的结果)时渲染子级并设置更新的偏移量。

标签: javascript reactjs ecmascript-6 react-lifecycle


【解决方案1】:

您遇到的问题正在发生,因为您对 API 的调用异步发生在 react 生命周期方法中。当 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 版本)

【讨论】:

    猜你喜欢
    • 2020-04-28
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-08-03
    • 1970-01-01
    • 2019-12-04
    • 1970-01-01
    • 2021-09-27
    相关资源
    最近更新 更多