Reactjs Redux工具包:有两个连续的分派,后者依赖于前者
我有一个名为Reactjs Redux工具包:有两个连续的分派,后者依赖于前者,reactjs,typescript,redux,redux-toolkit,Reactjs,Typescript,Redux,Redux Toolkit,我有一个名为getRole的操作和一个名为getPoliciesFrom的操作getRole返回角色,而getPoliciesFrom返回附加到该角色的策略列表。然后我需要分派这些操作来支持一个特性 我在myuseEffect中分派getRole,并使用useSelector将角色作为状态 const-role=useSelector((状态:RootState)=>state.settings.role); //... useffect(()=>{ 调度(getRole()); },[发送];
getRole
的操作和一个名为getPoliciesFrom
的操作getRole
返回角色,而getPoliciesFrom
返回附加到该角色的策略列表。然后我需要分派这些操作来支持一个特性
我在myuseEffect
中分派getRole
,并使用useSelector
将角色
作为状态
const-role=useSelector((状态:RootState)=>state.settings.role);
//...
useffect(()=>{
调度(getRole());
},[发送];
现在,为了获得策略,我考虑了两个选项:要么添加一个条件检查以查看角色
是否为null,当它不为null时,将getPoliciesFrom
作为参数传入角色
。这看起来像这样:
const role = useSelector((state: RootState) => state.settings.role);
useEffect(() => {
dispatch(getRole());
if(role) {
dispatch(getPoliciesFrom(role));
}
}, [dispatch]);
或我使用第一次发送返回的承诺,并将第二次发送附加到中,然后在承诺解决时
。看起来像这样
useEffect(() => {
dispatch(getRole()).then(result => dispatch(getPoliciesFrom(result))
}, [dispatch]);
两者似乎都在起作用。但是对于第二种方法,我的ts编译器对我大喊大叫,因为我附加了,然后,说
类型“AsyncThunkAction”上不存在属性“then”
但是我确实从getRole
返回了结果。这是它的代码
export const getRole = createAsyncThunk(
"settings/getRole",
async () => {
let response: GetServiceRoleForAccountResponse;
try {
response = await api.getServiceRoleForAccount().promise();
} catch (error) {
if (
error.statusCode === notAssociatedStatusCode &&
error.message === notAssociatedErrorMessage
) {
return { role: null };
}
throw error;
}
return { role: response.role };
}
);
此外,我不确定如何正确键入从承诺中获得的结果
最重要的是,这里哪种方法更好?您需要在getRole中返回结果,下面是一个thunk操作返回解析为值的承诺的工作示例:
const{Provider,useDispatch,useSelector}=ReactRedux;
const{createStore,applyMiddleware,compose}=Redux;
常量初始状态={
数字:0,
};
//动作类型
常数OK=‘OK’;
//动作创造者
常数ok=(数值)=>(调度)=>
//还愿
新承诺((决议)=>
设置超时(()=>{
派遣({
类型:好的,
有效载荷:num,
});
//将承诺分解为价值
解析(num);
}, 2000)
);
const reducer=(状态,{type,payload})=>{
如果(类型===OK){
返回{num:payload};
}
返回状态;
};
//选择器
const selectNum=(state)=>state.num;
//使用redux开发工具创建存储
康斯特康塞恩汉斯酒店=
窗口。uuu REDUX_vtools_uextension_uuucompose_uu124; COMPOSE;
const store=createStore(
减速器,
初始状态,
复合致癌物(
applyMiddleware(
({dispatch,getState})=>(下一步)=>(操作)=>
动作类型===‘功能’
?行动(调度、获取状态)
:下一步(行动)
)
)
);
常量应用=()=>{
const num=使用选择器(selectNum);
const dispatch=usedpatch();
React.useffect(()=>{
分派(ok(88))。然后((num)=>
log('num这里是:',num)
);
},[发送];
log('render中的num:',num);
返回字符串(num);
};
ReactDOM.render(
,
document.getElementById('root'))
);代码>
确保在getRole中返回结果:const getRole=arg=>dispatch=>{return async。然后((role)=>{dispatch(someAction);return role;})}
谢谢您的回复。我确实从getRole
返回了结果。我已经更新了我的答案,添加了getRole
外观的片段。顺便问一下,你认为哪种方法更好?