[英]Store.Dispatch() Resetting Redux Store
dispatch(action()) to trigger an action from outside my react component. dispatch(action()) 从我的反应组件外部触发一个动作。 It is working correctly in that it is triggering my action and updating the new item in my store.
它工作正常,因为它正在触发我的操作并更新我商店中的新项目。 The problem is that it seems to be completely resetting everything else in my store, which to me at least makes it more of a problem than its worth.
问题是它似乎完全重置了我商店中的所有其他东西,这至少对我来说是一个问题而不是它的价值。
Worth noting: I am using nextjs.值得注意的是:我正在使用 nextjs。
Here is a basic idea of my flow:这是我的流程的基本思想:
I have a utils folder with a service where I am dispatching this action from:我有一个带有服务的 utils 文件夹,我正在从以下位置分派此操作:
import store from './store';
store.dispatch(myAction());
I have my actions我有我的行动
export const myAction = () => ({
type: HELP_ME,
payload: true,
});
const initialState = {
reducerVar: fase,
otherExistingVar: {},
otherExistingVarTwo: null,
otherExistingThree:null,
otherExistingVarFour: false,
};
const myReducer = (state = initialState, action) => {
switch (action.type) {
case HELP_ME: {
const reducerVar = action.payload;
}
default: {
return state;
}
}
};
export default myReducer;
I am not sure if I am misusing store.dispatch() because I dont see why anyone would use this technique if it completely wipes out the existing data in the store.我不确定我是否误用了 store.dispatch() 因为我不明白为什么有人会使用这种技术,如果它完全清除了商店中的现有数据。 Or is there a better way to trigger this simple action from outside my component.
或者有没有更好的方法可以从我的组件外部触发这个简单的操作。
Basically I want to dispatch this action without completely wiping out my store just like I would dispatch the action if I were in a component.基本上我想在不完全清除我的商店的情况下调度这个动作,就像如果我在一个组件中我会调度这个动作一样。
Thank You!谢谢你!
What you are trying to do is fine.你正在尝试做的很好。 But your reducer must return the whole state with your change done by the action like below.
但是您的减速器必须通过如下操作完成更改后返回整个状态。
const myReducer = (state = initialState, action) => {
switch (action.type) {
case HELP_ME:
const reducerVar = action.payload;
return {...state, reducerVar }
default:
return state;
}
};
you should return the state with value in reducer like this.你应该像这样在reducer中返回带有值的状态。
const myReducer = (state = initialState, action) => {
switch (action.type) {
case HELP_ME: {
return {...state, reducerVar : action.payload}
}
default: {
return state;
}
}
};
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.