如何将Redux Toolkit中createAsyncThunk返回的响应数据传递给组件?
如何在验证组件中访问login_response
步骤1:完善userSlice的状态管理
你的userSlice.js目前仅定义了异步action,需要补充状态结构和异步逻辑的处理,将登录响应存入Redux store:
import { createSlice, createAsyncThunk } from '@reduxjs/toolkit'; // 保留原loginUser异步action,修正两处逻辑错误 export const loginUser = createAsyncThunk( 'users/login', async ({ email, password }, thunkAPI) => { try { const response = await fetch( 'my_url', { method: 'POST', headers: { Accept: 'application/json', 'Content-Type': 'application/json', }, body: JSON.stringify({ email, password }), } ); const login_response = await response.json(); console.log('response login', login_response); if (response.status === 200) { console.log('success from here') // 可选:将token存入localStorage // localStorage.setItem('token', login_response.token); return login_response; } else { // 原代码中data变量未定义,改为login_response return thunkAPI.rejectWithValue(login_response); } } catch (e) { // 处理网络错误,避免e.response为undefined的情况 const errorData = e.response?.data || { message: '网络请求失败' }; console.log('Error', errorData); return thunkAPI.rejectWithValue(errorData); } } ); // 定义slice初始状态 const initialState = { loginResponse: null, isLoading: false, error: null }; // 创建userSlice并处理异步action的状态变化 const userSlice = createSlice({ name: 'user', initialState, reducers: {}, extraReducers: (builder) => { builder // 登录请求成功,将响应存入state .addCase(loginUser.fulfilled, (state, action) => { state.loginResponse = action.payload; state.isLoading = false; state.error = null; }) // 登录请求中,标记加载状态 .addCase(loginUser.pending, (state) => { state.isLoading = true; state.error = null; }) // 登录请求失败,存储错误信息 .addCase(loginUser.rejected, (state, action) => { state.error = action.payload; state.isLoading = false; }); } }); export default userSlice.reducer;
步骤2:在验证组件中获取login_response
在验证组件中,使用Redux的useSelector钩子读取store中的登录响应,同时可通过useDispatch触发登录操作(如果验证组件需要主动发起登录):
import { useSelector, useDispatch } from 'react-redux'; import { loginUser } from '../features/user/userSlice'; const VerificationComponent = () => { // 从store中获取登录响应、加载状态和错误信息 const { loginResponse, isLoading, error } = useSelector(state => state.user); const dispatch = useDispatch(); // 示例:若需在验证组件中发起登录请求 const handleLogin = async (email, password) => { await dispatch(loginUser({ email, password })); }; // 根据状态渲染内容 if (isLoading) { return <div>登录中...</div>; } if (error) { return <div>登录失败:{error.message}</div>; } if (loginResponse) { // 直接访问login_response的字段,比如token、用户信息等 return ( <div> <h3>登录成功</h3> <p>用户ID:{loginResponse.userId}</p> <p>授权Token:{loginResponse.token}</p> </div> ); } return <div>请先完成登录</div>; }; export default VerificationComponent;
核心逻辑说明
- 登录组件触发
loginUser异步action后,Redux会自动处理请求的pending/fulfilled/rejected状态,并将响应存入store.user.loginResponse - 验证组件通过
useSelector订阅store状态,就能实时获取最新的login_response - 同步处理加载和错误状态,可避免页面出现异常或无反馈的情况
内容的提问来源于stack exchange,提问作者Geo Mukkath
相关产品推荐
相关产品推荐

