当 props 具有相同值时,react - 强制 componentDidUpdate()

Bik*_*koK 5 javascript reactjs react-redux

在我的组件中,我尝试将接收到的道具与当前状态同步,以便从外部可见(我知道这是一种反模式,但我还没有找到另一种解决方案。我非常愿意接受建议!)。

无论如何,这就是我所拥有的:

export class PopupContainer extends React.Component {
  state = {
    show: false,
  };

  shouldComponentUpdate(nextProps, nextState) {
    if (this.props.show === nextProps.show) return true;
    return true;
  }

  componentDidUpdate(prevProps, prevState, snapshot) {
    // if popup shown, fade it out in 500ms
    if (this.props.show !== prevProps.show)
      this.setState({ show: this.props.show });

    if (this.state.show) {
      setTimeout(() => this.setState({ show: false }), 2000);
    }
  }

  render() {
    return <Popup {...{ ...this.props, show: this.state.show }} />;
  }
}
Run Code Online (Sandbox Code Playgroud)

在我的外部组件中,我正在渲染容器:

<PopupContainer
          show={this.state.popup.show}
          message={this.state.popup.message}
          level={this.state.popup.level}
        />
Run Code Online (Sandbox Code Playgroud)

现在,当我最初设置this.state.showtrue时,它可以工作,但是每个连续的分配(中间也true没有任何false分配)都不起作用。componentdidUpdate()即使道具的价值相同,我如何强制射击?shouldComponentUpdate()似乎没有解决问题。

谢谢你!

编辑:我注意到该render()方法仅在父元素中调用。看起来,由于子项的属性没有变化,因此 React 甚至不需要重新渲染子项,这在某种程度上是有道理的。但我怎样才能强迫他们重新渲染呢?

bri*_*nch 1

这是一种黑客行为,但它对我有用。

在幼儿班里

在构造函数中添加一个属性到 state - 让我们调用它myChildTrigger,并将其设置为空字符串:

this.state = {
   ...
   myChildTrigger: ''
}
Run Code Online (Sandbox Code Playgroud)

然后将其添加到componentDidUpdate

componentDidUpdate(prevProps) {
   if(this.state.myChildTrigger !== this.props.myParentTrigger) {

      // Do what you want here

      this.setState({myChildTrigger: this.props.myParentTrigger});
   }
}
Run Code Online (Sandbox Code Playgroud)

在父类中

在构造函数中添加一个myParentTrigger状态:

this.state = {
   ...
   myParentTrigger: ''
}
Run Code Online (Sandbox Code Playgroud)

在 render 方法中,将其添加为 prop,如下所示:

<ChildClass ... myParentTrigger={this.state.myParentTrigger} />
Run Code Online (Sandbox Code Playgroud)

现在,您只需设置一个新值即可触发调用componentDidUpdate以执行 if 语句内的任何内容,例如:myParentTrigger

this.setState({ myParentTrigger: this.state.myParentTrigger + 'a' });
Run Code Online (Sandbox Code Playgroud)