javascript - Redux以前的状态已经有了新的状态值无法理解为什么

标签 javascript reactjs redux react-redux state

我是 React Redux 环境的新手,目前面临一个我难以理解的问题。

我制作了一个包含链接列表的页面。 当我单击“添加链接”按钮时,我可以将链接添加到列表中,然后会出现一个带有表单的模式。

当我提交表单时,当我从 link.utils.js 触发 addLinkItem 方法时,新链接将添加到 firebase

我正在使用react-thunk在firebase添加成功时进行调度,这是一个更新我的链接状态的操作。

我的问题是,此时我的 prevState 已经有了我的 nextState 值,所以问题是我的组件 LiSTLink 没有用这个新状态刷新。

我希望我说得足够清楚

  • Firebase
  • React、Redux、redux-logger、redux-thunk

您可以找到此存储库的所有项目:https://github.com/FrancoisSilab/klaxoon-test-bookmarks/blob/master/README.md

const handleSubmit = event => {
    event.preventDefault();
    addLinkItem(inputValues);
  };

add-link-modal.component.jsx

export const addLinkItem = (link) => {
  return dispatch => {
    // On obtient la référence de la collection links
    const colRef = firestore.collection("links");
    // On ajoute le nouveau linkItem comme nouveau document
    colRef
      .add(link)
      .then(function(docRef) {
        console.log("Document successfully written!");
        link["id"] = docRef.id;
        dispatch(addLinkItemAction(link));
        dispatch(resetInput());
      })
      .catch(function(error) {
        console.error("Error writing document: ", error);
      });
  };
};

links.utils.js

export const addLinkItemAction = (link) => ({
  type: LinksActionsTypes.ADD_LINK,
  payload: link
});

links.actions.js

const INITIAL_STATE = {
  linksItems: []
};

const linkReducer = (state = INITIAL_STATE, action) => {
  switch (action.type) {
    case LinksActionsTypes.GET_LINKS:
      return {
        ...state,
        linksItems: action.payload
      };
      case LinksActionsTypes.ADD_LINK:
        state.linksItems.push(action.payload);
        return {
        ...state,
        linksItems: state.linksItems
      };
      case LinksActionsTypes.DELETE_LINK:
      return {
        ...state,
        linksItems: deleteLinkItem(state.linksItems, action.payload)
      };
    default:
      return state;
  }
};

export default linkReducer;

links.reducer.jsx

最佳答案

问题是你正在改变状态。而不是插入旧数组:

state.linksItems.push(action.payload);
return {
  ...state,
  linksItems: state.linksItems
};

...创建数组的副本并将其添加到该副本中。

const newLinkItems = [...state.linkItems, action.payload];
return {
  ...state,
  linkItems: newLinkItems
}

关于javascript - Redux以前的状态已经有了新的状态值无法理解为什么,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58146160/

相关文章:

javascript - 为什么 React 的 onClick 函数需要独特的语法?与其他事件触发器相比?

reactjs - 如何在React Native Navigator中传递参数?

javascript - 为什么所有的 lodash 最终都出现在我的 webpack 构建中?

javascript - 在 react/redux/saga/selector 设置中与 'what goes where' 作斗争

javascript - 一段代码就能将所有表单转换为 AJAX 表单?

javascript - WP - 在 JS 中获取 stylesheet_directory

javascript - 将数据作为 props 传递时未定义

javascript - 使用 reactjs 在 redux 中未定义调度

javascript - 响应式设计 - 在这种情况下移动和桌面布局之间的反向 css 效果

javascript - 来自本地数组的 ExtJs Combobox