我有几组复选框,它们的作用是选中和取消选中某些选项中的某个框。但是,当我分派一个操作时,什么也没有发生。有效负载和类型对我来说都是有效的。
下面是复选框设置代码。
function CheckboxOptions(props:NamedOptions<any>): JSX.Element {
function handleCheckboxChange(e, index:number) {
...
if(isChecked){
const actionName = "CHECK_" + itemName;
createStudyStore.dispatch({type: actionName, payload:index});
}
else{
const actionName = "UNCHECK_" + itemName;
createStudyStore.dispatch({type: actionName, payload:index});
}
}
let checkboxes = props.options.map((option, i)=>{
...
return (<Grid>
<FormControlLabel control={<Checkbox onChange={(e)=>handleCheckboxChange(e,i)}/>} label={optionTxt}/>
</Grid>
);
});
return <>
{checkboxes}
</>;
};
类型和有效载荷是正确的,但我没有得到调度做任何事情。
以下是我的减速机工厂,因为我有许多复选框
function createNamedOptionsReducerWithNamedType(name=""){
return function namedOptionReducer(state:NamedOptions<any>, action:PayloadAction<number>): NamedOptions<any>{
switch (action.type){
case "CHECK_${name}":
state.value[action.payload] = true;
return state;
case "UNCHECK_${name}":
state.value[action.payload] = false;
return state;
default:
return state;
}
}
}
切片的创建方法如下
const open_variables_slice = createSlice({
name: "open_variables",
initialState: initial_form.open_variables,
reducers: getReducers(open_variable_keys, initial_form.open_variables)
})
getReducers返回一个归约器的Map,每个复选框集一个归约器,并在内部调用createNamedOptionsReducerWithNamedType。
我的减根器定义如下,并与我的商店相关联。
export const rootReducer = combineReducers({
open_variables : open_variables_slice.reducer,
independent_variables : independent_variables_slice.reducer,
ladder_variables : ladder_variables_slice.reducer,
})
export const createStudyStore = configureStore({reducer: rootReducer});
我不明白如何去调试这个.我已经打印了动作类型和有效负载,它匹配从我在reducer工厂打印出来的所谓有效动作类型.也许createSlice要求我用createAction创建的动作类型调用我的调度?或者rootReducer以某种方式命名了我的reducer?任何想法?感谢帮助!
1条答案
按热度按时间tgabmvqs1#
我在你的代码中发现了很多问题。
到目前为止,最大的一个是你在reducer中 mutating 状态,并且你必须 * 永远不要 * 在Redux中这样做:
(* 如果 * that最终在
createSlice
内部使用,那么这行代码是可以的。但是您使用的 Package 层和reducer生成层使您很难判断您实际在做什么。)另一个问题是,它看起来像你直接导入 * 一个 * Redux商店到组件(
createStudyStore.dispatch()
)中,并且你以这种方式命名它的事实表明这个应用中可能有 * 多个 * Redux商店。这些也是你不能用Redux做的事情。我实际上没有看到你的代码中有任何React-Redux的使用,比如
useSelector
。你可能只是在你发布的代码片段中省略了它,但是如果你没有使用它,UI肯定不会更新。我强烈建议你阅读我们核心文档中的“Redux Essentials”教程: