首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
MCP广场
社区首页 >问答首页 >在将道具传递给儿童之前,应检查api请求

在将道具传递给儿童之前,应检查api请求
EN

Stack Overflow用户
提问于 2018-05-11 12:41:26
回答 1查看 789关注 0票数 1

我有一个Parent组件和一个Child组件,我的操作可以在子组件中触发一些api调用,而在componentWillMount上,我签入了if条件--一些来自父级的props,并执行了一些触发器。如果条件为true,则触发呈现新组件的方法。问题是,在componentWillmount中的子组件中,props this.props.personthis.props.notFound是未定义的,但是在呈现和检查这个支持之前,我需要等待api请求。

父母:

代码语言:javascript
运行
复制
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,
)}

儿童:

代码语言:javascript
运行
复制
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)
EN

回答 1

Stack Overflow用户

发布于 2018-05-11 13:20:02

您所遇到的问题正在发生,因为您对API的调用发生了asynchronously对react生命周期方法的调用。当API响应返回时,第一次调用父组件的呈现方法,从而呈现子组件,然后调用该组件,该子组件将与父组件在使用API响应数据初始化之前传递给它的支持一起挂载。当API结果最终被返回并作为新的支持传递到子组件(父组件重新呈现的结果)时,它将不会触发componentWillMount生命周期,因为它已经挂载了。

您可以通过多种方式解决这一问题,这取决于您今后计划如何使用子组件。有几个解决办法:

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

代码语言:javascript
运行
复制
render() {
  this.state.value && <Child value={this.state.value} onNotValidId={() => this.renderNewComponent()} />
}

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

票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/50292600

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档