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

React函数式组件中Redux无法派发signIn action、payload未触发reducer问题

问题根因

  • 你没有使用connect注入到组件props中的signIn方法,直接调用了原始导入的action创建函数,没有和redux的dispatch绑定,自然不会触发reducer
  • 按钮的onClick事件直接执行了signIn方法,而非传递点击时才执行的回调函数,会导致组件渲染时就自动触发请求,而非点击触发
  • 额外问题:函数组件第一个参数是props对象,你声明成了state,会导致无法正确拿到redux注入的属性,且代码缺少useState的导入语句,reducer代码没有闭合switch和加default分支

修复代码

1. Login组件修正代码

// 补全useState导入
import { useState } from 'react';
import { connect } from 'react-redux';
import { signIn } from '../ducks/actions/adminActions'

// 第一个参数为props,从props中获取connect绑定好dispatch的signIn方法
const Login = (props: any) => {
    const [email, setEmail] = useState('');
    const [password, setPassword] = useState('');
    const onEmailChange = (event: any) => {
        setEmail(event.target.value)
    };
    const onPasswordChange = (event: any) => {
        setPassword(event.target.value)
    };
    return (
        <div>
            <h4>Email</h4>
            <input type="text" onChange={onEmailChange}/>
            <h4>Password</h4>
            <input type="password" onChange={onPasswordChange}/>
            {/* onClick改为回调函数,调用props里的signIn */}
            <button type="submit" onClick={() => props.signIn({email, password})}>Submit</button>
        </div>
    );
};
const mapStateToProps = (state: any) => {
    return {
        isSignedIn: state.auth.isSignedIn
    };
};
export default connect(
    mapStateToProps,
    { signIn }
)(Login);

2. Reducer补全代码

import { SIGN_IN, SIGN_UP } from "../actions/types";

const INITIAL_STATE = {
  isSignedIn: null,
  userId: null
};

export default (state = INITIAL_STATE, action: any) => {
  switch (action.type) {
    case 'SIGN_IN':
      return {...state, isSignedIn: true, userId: action.payload};
    // 补全SIGN_UP等其他case和默认分支
    default:
      return state;
  }
};

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.29 13:15:02