[英]extraReducers not working when I'm trying to watch for the action on my slice on the same file
每次发送 fillForm 操作时,我都试图触发额外的减速器。 但代码不工作。 有什么帮助吗?
export const userSelectSlice = createSlice({
name: "userSelect",
initialState: {
name: localStoreData?.name || "",
salary: localStoreData?.salary || "",
job: localStoreData?.job || "",
location: localStoreData?.location || "",
eligibility: localStoreData?.eligibility || "",
},
reducers: {
fillForm: (state, action) => {
state.name = action.payload.name;
state.salary = action.payload.salary;
state.job = action.payload.job;
state.location = action.payload.location;
localStorage.setItem(
"userSelect",
JSON.stringify({
name: action.payload.name,
salary: action.payload.salary,
job: action.payload.job,
location: action.payload.location,
})
);
},
},
extraReducers: (builder) => {
builder.addCase(createAction('fillForm'), (state, action) => {
// extra reducer code goes here
console.log('sdcjknsdcjnsdjhcbsdjhb')
state.eligibility = 'sdckjsdcjnsdjcbdshjcb'
});
},
});
我尝试了几种方法,但没有任何帮助
如文档中所述:
用 extraReducers 指定的 reducers 意味着引用“外部”操作
如果来自 reducers 和 extraReducers 的两个字段碰巧以相同的操作类型字符串结尾,则来自 reducers 的 function 将用于处理该操作类型。
您提供的示例就是这种情况。 您不能在同一个切片中处理两次相同的操作。 ExtraReducers
旨在允许您响应切片生成的类型之外的其他操作类型。 所以你可以
state.eligibility = 'sdckjsdcjnsdjcbdshjcb'
到现有的减速器export const userSelectSlice = createSlice({
name: "userSelect",
initialState: {
//...
},
reducers: {
fillForm: (state, action) => {
// ... do your stuff
console.log('fillForm slice reducer')
state.eligibility = 'sdckjsdcjnsdjcbdshjcb' // add code from extra reducers
},
},
});
export const someOtherSlice = createSlice({
name: 'otherSlice',
initialState: {
//...
},
reducers: {
fillForm: (state, action) => {
// eslint-disable-next-line no-console
console.log('fillForm slice reducer')
}
},
extraReducers: (builder) => {
builder.addCase(createAction('fillForm'), (state, action) => {
// extra reducer code goes here
// eslint-disable-next-line no-console
console.log('fillForm extraReducers')
})
}
})
export const fillFormExtra = createAction('fillForm')
export const userSelectSlice = createSlice({
name: 'userSelect',
initialState: {
eligibility: ''
},
reducers: {
fillForm: (state, action) => {
// eslint-disable-next-line no-console
console.log('fillForm slice reducer')
}
},
extraReducers: (builder) => {
builder.addCase(createAction('fillForm'), (state, action) => {
// extra reducer code goes here
// eslint-disable-next-line no-console
console.log('fillForm extraReducers')
state.eligibility = 'sdckjsdcjnsdjcbdshjcb'
})
}
})
并分别派遣
dispatch(userSelectSlice.actions.fillForm({}))
dispatch(fillFormExtra())
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.