尽管状态被更新,Redux 不会重新渲染组件

时间:2021-07-28 21:26:44

标签: reactjs redux react-redux state

我可以看到我的状态正在使用 console.log 进行更新。如果我使用另一个导致组件重新渲染的功能,我就会看到更改。因此,“按钮”状态(显示浏览器中的按钮)会更新但不会显示,直到其他原因导致它在浏览器中重新呈现。我已经尝试了几乎所有方法来确保我正确复制了状态,但似乎都没有解决问题。

减速器:

case getType(actions.editButton):
  if (previousState.currentButton !== null && previousState.currentList !== null) {
    let oldButtonList = _.cloneDeep(previousState.buttons);
    oldButtonList = oldButtonList.filter((button) => button.buttonType !== previousState.currentButton?.buttonType);
    let newList = _.cloneDeep(previousState.currentList);
    const index = newList.indexOf(previousState.currentButton);
    const newButton = _.cloneDeep(previousState.currentButton);
    newButton.label = action.payload;
    newList[index] = newButton;
    newList = newList.concat(oldButtonList);
    console.log('Old List', previousState.buttons);
    console.log('New list', newList); //Fix: Is being updated, but not re-rendering
    return { ...previousState, buttons: newList, currentList: newList, currentButton: newButton };
  }
  return previousState;

组件:

const ButtonList: React.FC<Props> = ({ buttons, listType, template }) => {
const useStyles = getThemeFromTemplate(template);
const classes = useStyles();
return (
  <div className={listType === Variant.Primary ? classes.PrimaryListContainer : classes.SecondaryListContainer}>
  {buttons
    .filter((button) => button.buttonType === listType)
    .sort((a, b) => (a.displayOrder > b.displayOrder ? 1 : -1))
    .map((button: HPButton, index: number) => {
      if (index < getMaxListSize(template, listType)) {
        return (
          <div
            key={index}
            className={
              listType === Variant.Primary ? classes.PrimaryButtonContainer : classes.SecondaryButtonContainer
            }
          >
            <HomepageButton button={button} />
          </div>
        );
      } else return null;
    })}
</div>
  );
};

const mapStateToProps = (state: State, ownProps: any) => {
const { variant: listType } = ownProps;
return {
  buttons: state.homepage.homepageReducer.buttons,
  template: state.homepage.homepageReducer.template,
  listType,
  };
};

类型道具 = ReturnType;

导出默认连接(mapStateToProps)(ButtonList);

操作:

export const editButton = createStandardAction('EDIT_BUTTON')<string>();
export const actions = { selectButton, deleteButton, addButton, editButton, changeOrder, changeTemplate };

export type Action = ActionType<typeof actions>;

export default actions;

0 个答案:

没有答案