[英]How can I control dispatch actions in Redux toolkit with React Native?
If i run my code, dispatch(addPost(formData));如果我运行我的代码,dispatch(addPost(formData)); is executed and while thunkAPI is running navigation.navigate('PostList');被执行,而 thunkAPI 正在运行 navigation.navigate('PostList'); is executed and moves to the PostList screen before the actions are finished.在操作完成之前执行并移动到 PostList 屏幕。
But what i want to do is When I execute the sendPostfunc function, dispatch(addPost(formData));但我想做的是当我执行 sendPostfunc function, dispatch(addPost(formData)); is firstly triggered, and secondly, thunkAPI.dispatch(postSlice.actions.purePost());首先被触发,其次,thunkAPI.dispatch(postSlice.actions.purePost()); is executed and thirdly, thunkAPI.dispatch(loadPosts());被执行,第三,thunkAPI.dispatch(loadPosts()); is executed and the action is complete, after that navigation.navigate('PostList');被执行并且动作完成,在那之后 navigation.navigate('PostList'); I want to make it run and go to the PostList Screen.我想让它运行 go 到 PostList 屏幕。
How can i fix my code?我该如何修复我的代码?
this is my code这是我的代码
(Post.tsx) (后.tsx)
const sendPostfunc = useCallback(async () => {
dispatch(addPost(formData));
navigation.navigate('PostList');
}, [dispatch,navigation]);
(action.tsx) (action.tsx)
export const addPost = createAsyncThunk(
'post/addPost',
async (data: Object, thunkAPI) => {
try {
const response = await axios.post('/post/addPost', data);
thunkAPI.dispatch(postSlice.actions.purePost());
thunkAPI.dispatch(loadPosts());
return response.data;
} catch (error: any) {
return thunkAPI.rejectWithValue(error.response.data);
}
},
);
navigate
call into addPost
(pass it as an additional argument, something like redirectTo
, a callback that will execute after posts have been loaded.将navigate
调用移动到addPost
(将其作为附加参数传递,类似于redirectTo
,一个将在加载帖子后执行的回调。loadPosts
is also a thunk, let it return a promise so you can await
this work being done inside addPost
- explained here: https://redux.js.org/usage/writing-logic-thunks#returning-values-from-thunks假设loadPosts
也是一个 thunk,让它返回一个 promise 这样你就可以await
这个工作在addPost
中完成 - 在这里解释: https://redux.js.org/usage/writing-logic-thunks#returning-values-from-砰的一声
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.