React中传入函数组件的Props函数未调用问题排查
问题解决:React函数组件传入的login函数无法调用
核心问题分析
- Redux connect覆盖了props:你在
Login组件中使用connect(null, {})(Login),但未将loginaction creator映射到组件props,同时在App.tsx中直接传递login作为props,这会被connect返回的高阶组件覆盖,导致组件内拿到的login并非期望的函数。 - Action参数不匹配:
auth.tsx中login函数接收的参数是username,但表单收集的是email,即使函数执行,后端也可能无法正确处理请求。
解决方案步骤
1. 修正Login组件的Redux连接
移除App.tsx中给Login组件传递login props的代码,改为通过connect的第二个参数(mapDispatchToProps)将login action绑定到组件props:
修改Login.tsx:
import { FunctionComponent, useState } from "react"; import { Link } from "react-router-dom"; import { connect } from "react-redux"; // 导入login action,注意路径匹配实际项目结构 import { login } from "../../actions/auth"; interface IFormData { email: string; password: string; } interface ILoginProps { login: (email: string, password: string) => void; } const Login: FunctionComponent<ILoginProps> = ({ login }) => { const [formData, setFormData] = useState<IFormData>({ email: "", password: "", }); const { email, password } = formData; const onChange = (e: React.ChangeEvent<HTMLInputElement>) => setFormData({ ...formData, [e.target.name]: e.target.value, }); const onSubmit = (e: React.FormEvent<HTMLFormElement>) => { e.preventDefault(); login(email, password); }; return ( <div> <h1>Sign In</h1> <p>Sign into your account</p> <form onSubmit={onSubmit}> <div> <input type="email" placeholder="email" name="email" value={email} onChange={onChange} required /> </div> <div> <input type="password" placeholder="password" name="password" value={password} onChange={onChange} minLength={6} required /> </div> <button type="submit"> Login </button> </form> <p> Don't have an account? <Link to="/signup">Sign Up</Link> </p> <p> Forgot your password? <Link to="/reset-password">Reset Password</Link> </p> </div> ); }; // 将login action映射到组件props export default connect(null, { login })(Login);
修改App.tsx中Login组件的渲染:
<Route path="/login" element={<Login />} />
2. 修正auth.tsx中的login action参数
如果后端登录接口接收的是email而非username,修改login action的请求体:
export const login = (email: string, password: string) => async (dispatch: any) => { const config = { headers: { 'Content-Type': 'application/json' } }; // 将username改为email,匹配表单传递的值 const body = JSON.stringify({ email, password }); console.log("yay"); try { const res = await axios.post(`${process.env.REACT_APP_API_URL}/api/jwt/create/`, body, config); dispatch({ type: LOGIN_SUCCESS, payload: res.data }); dispatch(load_user()); } catch (err) { dispatch({ type: LOGIN_FAIL }); } };
3. 验证函数执行
现在点击登录按钮后,login函数会被正确调用,你应该能看到console.log("yay")的输出,同时后端会收到对应的登录请求。
额外说明
- 使用Redux的
connect时,组件的props会被connect返回的高阶组件处理,直接从父组件传递的props如果和connect映射的props同名,会被覆盖。 - 确保你的Redux store配置正确,中间件包含
redux-thunk(因为你的action是异步函数),否则异步action无法执行。
内容的提问来源于stack exchange,提问作者Roitko
相关产品推荐
相关产品推荐

