0

我有一个组件可以触发一些依赖异步 API 请求的方法。我使用 componentWillmount 检查一些道具。如果这个道具是true我触发一些功能,否则为假。但问题是,第一次 prop 是undefined,只有过一段时间才会变成falseor true。如何检查它并等待请求解决?

componentWillMount = () => {
  this.props.init(parseInt(this.props.tagId, 16), this.props.accessToken);
  if (!this.props.notFound && !this.props.person) this.props.onFreeTag();
};
4

2 回答 2

1

使用componentWillReceiveProps生命周期函数,例如:

componentWillReceiveProps = (nextProps) => {
    if (!nextProps.notFound && !nextProps.person)
        nextProps.onFreeTag()
    }
}
于 2018-05-11T08:24:25.660 回答
1

看起来,当组件第一次加载或被调用时,您正在向它传递一些最初未定义的值,后来变得可用。例如,假设您有一个父组件,如下所示

class Parent extends React.Component {
    constructor() {
        this.state = {0}
    }

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

如您所见,最初状态没有属性value,因此Child将收到undefinedfor this.props.valueundefined只有当某些父函数像这样更改它时,它才会收到,

class Parent extends React.Component {
    constructor() {
        this.state = {0}
    }

    onAction() {
        this.setState({value: true})
    }

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

因此,如果在某些事件上,父调用OnAction它会改变状态,而 Child 将得到this.props.valuetrue但由于 Child 已经被渲染,componentWillMount钩子不会被触发,而是componentWillReceiveProps会被触发。因此,如果您想使用道具,请componentWillMount确保它在孩子的第一次渲染时通过,如果这不可能用于componentWillReceiveProps处理道具

于 2018-05-11T08:41:06.117 回答