You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

React+Redux登录表单:如何将用户输入数据传递至Reducer

解决React登录表单用户数据传递到Redux Reducer的问题

步骤1:修改authSlice的login reducer,支持接收payload

Redux Toolkit的createSlice生成的reducer可以通过action.payload获取传递过来的数据。你需要更新login reducer的定义,让它接收action参数,并将payload中的数据赋值给state:

export const authSlice = createSlice({
  name: "auth",
  initialState: { // 确保initialState有明确的初始值
    authenticated: false,
    token: null,
    currentUser: null
  },
  reducers: {
    login: (state, action) => {
      // 从action.payload中提取传递的用户凭证和token
      state.authenticated = true;
      state.token = action.payload.token;
      state.currentUser = action.payload.userCreds;
    },

    logout: (state) => {
      state.authenticated = false;
      state.token = null;
      state.currentUser = null;
    },
  },
});

步骤2:在LoginHandler中传递数据给login action

调用dispatch(login())时,将userCreds和生成的token作为参数传入,这些数据会被自动包装成action的payload:

// 移除组件内的useState,状态由Redux管理
// const [isAuthenticated, setIsAuthenticated] = useState(false);
// const [token, setToken] = useState(null);

const LoginHandler = (e) => {
  e.preventDefault();

  const userCreds = {
    email: email,
    password: password,
  };

  const newToken = Math.random().toString();
  
  // 将用户凭证和token作为payload传递给login action
  dispatch(login({ userCreds, token: newToken }));
};

步骤3:从Redux Store中获取状态(可选)

如果需要在组件中使用登录状态,用useSelector从store中读取:

import { useSelector } from 'react-redux';

// 在组件内
const { authenticated, token, currentUser } = useSelector(state => state.auth);

这样就能把用户输入的邮箱、密码,以及生成的token成功传递到authSlice的login reducer中,更新Redux的全局状态了。

内容的提问来源于stack exchange,提问作者Cypher

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.07 04:25:22