Reactjs 管理组件WilleReceiveProps和onChange功能之间的冲突
我正在使用其他人编写的相当复杂的react应用程序。我想为消息线程末尾的表单字段设置一个默认值 在加载所有数据之前,可能会多次调用子渲染函数。我的表单组件的默认值取决于线程中的最后一个值 因此,我在构造函数中设置replyType,在getReplyType中有一些基于当前道具计算的逻辑:Reactjs 管理组件WilleReceiveProps和onChange功能之间的冲突,reactjs,Reactjs,我正在使用其他人编写的相当复杂的react应用程序。我想为消息线程末尾的表单字段设置一个默认值 在加载所有数据之前,可能会多次调用子渲染函数。我的表单组件的默认值取决于线程中的最后一个值 因此,我在构造函数中设置replyType,在getReplyType中有一些基于当前道具计算的逻辑: constructor(props) { super(props); this.state = { replyType: this.getReplyType(), }
constructor(props) {
super(props);
this.state = {
replyType: this.getReplyType(),
};
}
如果我们花了3次时间才从父级获取所有数据,那么这将不会呈现正确的值。因此,我使用这样的调用来更新表单中的值:
componentWillReceiveProps(nextProps) {
this.setState({
replyType: this.getReplyType(nextProps),
});
}
这让我得到了我想要的初始状态。问题是componentWillReceiveProps每次都被调用,包括在用户手动选择之后。它不会覆盖选择文本,但会破坏CSS呈现方式的一些逻辑
changeReplyType = ({ value }) => {
this.setState({
replyType: value,
});
}
问题:如果更改是由事件处理程序触发的,是否有方法阻止组件WillReceiveProps运行?我必须在组件WillReceiveProps中使用if语句和新的prop
componentWillReceiveProps(nextProps) {
// setState when props change from pending to not pending
// prevents function from being called when changeReplyType updates state
if (!nextProps.isPending && this.props.isPending) {
this.setState({
replyType: this.getReplyType(nextProps),
});
}
}