React Redux报错:Cannot read property 'dispatch' of undefined 求助
Hey there, let's fix that Cannot read property 'dispatch' of undefined error you're running into when triggering handleInputChange!
The core issue here is that your class method handleInputChange doesn't have its this context bound to the component instance. When the onChange event fires, this no longer points to your SuperSignupScreenImpl component, making this.props undefined—hence the error when trying to access dispatch.
3 Simple Fixes
Fix 1: Define the method with an arrow function
Arrow functions automatically bind the current context's this, which is the cleanest approach:
class SuperSignupScreenImpl extends React.PureComponent<SignupScreenProps & {dispatch: Dispatch<{}>}, {}> { render() { return( <> <TextField hintText="Name" onChange={this.handleInputChange} name="name" /> <RaisedButton label="Submit" primary={true}/> </> ); } // Use arrow function to auto-bind this handleInputChange = (event) => { const target = event.target; const value = target.value; this.props.dispatch(updateForm(value)); } }
Fix 2: Manually bind this in the constructor
If you prefer traditional class method syntax, explicitly bind this in the constructor:
class SuperSignupScreenImpl extends React.PureComponent<SignupScreenProps & {dispatch: Dispatch<{}>}, {}> { constructor(props) { super(props); // Bind this to the method this.handleInputChange = this.handleInputChange.bind(this); } render() { return( <> <TextField hintText="Name" onChange={this.handleInputChange} name="name" /> <RaisedButton label="Submit" primary={true}/> </> ); } handleInputChange(event){ const target = event.target; const value = target.value; this.props.dispatch(updateForm(value)); } }
Fix 3: Wrap the call in an arrow function directly in onChange
You can avoid modifying the method itself by wrapping it in an arrow function during the event binding:
render() { return( <> <TextField hintText="Name" onChange={(e) => this.handleInputChange(e)} name="name" /> <RaisedButton label="Submit" primary={true}/> </> ); }
Note: This creates a new arrow function on every render, so use it sparingly in performance-sensitive components—stick to the first two fixes for better optimization.
Quick Bonus Fix
I spotted a small typo in your component props: you're using HomeScreenProps but exported SignupScreenProps. Correct that to avoid type errors:
class SuperSignupScreenImpl extends React.PureComponent<SignupScreenProps & {dispatch: Dispatch<{}>}, {}> { // ... rest of your code }
内容的提问来源于stack exchange,提问作者sachsure

