首页 > 解决方案 > Redux 连接的反应应用程序 - 在我的副作用完成之前我如何不渲染它?

问题描述

反应 16.3 Redux 3.7.2

在我调用一个通过副作用(AJAX)componentDidMount填充道具的动作。(mapDispatchToProps)

我的问题是它重用了 redux 中的旧道具 - 先渲染,然后在更新到达后重新渲染mapDispatchToProps

我不想让这个子组件记住它的状态或道具——我每次都需要它是一张白纸。

该文档指出该组件在卸载时被销毁,但情况似乎并非如此,因为当您转到此页面或您在页面上并重新加载时,状态有所不同。

因为当你重新加载时没有数据,所以页面必须等待副作用完成。

不幸的是,我无法为您提供代码示例 - 但任何接触过这种奇怪行为的人都应该认出我的描述......

标签: javascriptreactjsreduxreact-redux

解决方案


您的组件可能会以“旧”状态重新渲染,因为这是您存储在 redux 中的状态,并且正在传递给组件

您可以做的是触发一个componentWillUnmount破坏该状态的 redux 操作。

EG(伪伪代码):

减速器:

const initialState = { counter: 0 };

const myReducer = (state = initialState, action) => {
  switch(action.type) {
    case 'DO_SOMETHING':
      return {
        ...state,
        counter: state.counter + 1
      };

    case 'CLEAN_STATE':
      return initialState;
  }
}

零件:

class MyComponent extends React.Component {
  render () {
    return (
      <div>
        <span>{this.props.counter}</span>
        <button onClick={triggerActionThatCausesDO_SOMETHING} />
      </div>
    );
  }

  componentWillUnmount () {
    triggerActionThatCausesCLEAN_STATE();
  }
}

推荐阅读