我是 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/