React-Redux报错:Cannot read property 'props' of undefined 求助
Hey there, let's break down why you're running into this error and how to fix it quickly.
The Root Cause
This error pops up because the this context inside your axios.post .then callback isn't pointing to your React component instance anymore. When you use a regular function as the callback, it creates its own this context—so trying to access this.props results in undefined.
Quick Fixes to Try
1. Use an Arrow Function for the .then Callback
Arrow functions inherit the this context from the surrounding scope (your component), so this will immediately fix the issue. Update your handleSubmit method like this:
handleSubmit(e) { console.log("form submit"); e.preventDefault(); const forms = new FormData(e.target); axios.post("http://localhost:8080/reactLogin", forms) .then((res) => { // Changed to arrow function here console.log(res.data); this.props.loginSubmit(res.data); }) .catch(err => console.log(err)) }
2. Bind handleSubmit in the Constructor
If you prefer using regular functions, you can explicitly bind the component's this to the handleSubmit method in your component's constructor:
constructor(props) { super(props); // Bind the method to the component instance this.handleSubmit = this.handleSubmit.bind(this); } handleSubmit(e) { console.log("form submit"); e.preventDefault(); const forms = new FormData(e.target); axios.post("http://localhost:8080/reactLogin", forms) .then(res => { console.log(res.data); this.props.loginSubmit(res.data); }) .catch(err => console.log(err)) }
3. Define handleSubmit as an Arrow Function (Class Field Syntax)
Another clean approach is to define your handleSubmit method as an arrow function directly in the class. This automatically binds the component's this to the method:
handleSubmit = (e) => { console.log("form submit"); e.preventDefault(); const forms = new FormData(e.target); axios.post("http://localhost:8080/reactLogin", forms) .then(res => { console.log(res.data); this.props.loginSubmit(res.data); }) .catch(err => console.log(err)) }
Quick Note on Your mapStateToProps
Also, I noticed you wrote mapStateProps instead of the standard mapStateToProps—while this might not be causing the current error, double-check that you're using the correct name when connecting your component to Redux with connect(mapStateToProps, mapDispatchToProps)(YourComponent) to avoid future issues.
内容的提问来源于stack exchange,提问作者Pranab V V

