使用useEffect响应Redux状态更改

时间:2019-10-18 05:18:22

标签: javascript reactjs typescript state lifecycle

每次道具更改时,我都需要运行一些东西。使用React类,我可以做到:

componentDidUpdate(prevProps) {
  if (prevProps.x !== this.props.x) {
    // do something
  }
}

我知道在钩子中它应该是useEffect并带有一个依赖项数组:

useEffect(() => {
  // do something
}, [props.x])

但是我需要做一些超出useEffect范围的事情。

就我而言,我需要onChange中的一个函数仅在Redux状态更改时才能运行:

const Editor: React.FC = () => {
  const { options } = useSelector((state: RootState) => state.settings)

  <CodeMirror
    onChange={(editor, data, value) => {
    // I need to do something only when prev state is different
    if (prevOptions !== options) {
      editor.refresh()
    }
  />

除了可能在发生更改时在功能组件外部设置一个标志并手动将其设置回去之外,我不知道该怎么做。

0 个答案:

没有答案