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

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.15 07:19:16