React/Redux/Thunk中按钮点击press函数props未定义报错求助
解决React组件中点击事件函数无法读取props的问题
嘿,这个问题我太熟悉啦!你遇到的Uncaught TypeError: Cannot read property 'props' of undefined,核心原因就是点击事件回调的this上下文没有绑定到组件实例上。
为什么会这样?
当你在componentWillMount里调用this.press()时,这个方法是通过组件实例直接调用的,this自然指向组件本身,所以能正常访问props。但把press作为onClick的回调传给按钮时,函数会被“独立调用”,此时this默认是undefined(严格模式下),自然就找不到props了。
三种快速解决方法
1. 用箭头函数定义press方法(推荐)
箭头函数会自动继承外层作用域的this,也就是组件实例,这样不管怎么调用,this都不会丢失:
class StuffList extends React.Component { // 用类属性语法定义箭头函数 press = () => { // 现在可以正常访问this.props啦 this.props.stuffActions.yourAction(); } render() { return <button onClick={this.press}>点击触发</button>; } }
注意:这种语法需要Babel支持,要确保你的项目配置了@babel/plugin-proposal-class-properties插件。
2. 在构造函数中手动绑定this
这是传统的绑定方式,在组件初始化时把press的this绑定到组件实例:
class StuffList extends React.Component { constructor(props) { super(props); // 手动绑定this this.press = this.press.bind(this); } press() { this.props.stuffActions.yourAction(); } render() { return <button onClick={this.press}>点击触发</button>; } }
3. 在onClick中用箭头函数包裹
这种方式不用修改press方法本身,直接在回调里用箭头函数调用:
class StuffList extends React.Component { press() { this.props.stuffActions.yourAction(); } render() { // 用箭头函数包裹,确保this指向组件 return <button onClick={() => this.press()}>点击触发</button>; } }
不过这种方式每次渲染都会创建一个新的箭头函数,性能敏感的场景下尽量避免。
验证一下
不管用哪种方法,修改后点击按钮时,press里的this都会指向组件实例,就能正常访问props里的Redux action creators啦!
内容的提问来源于stack exchange,提问作者user2130951
相关产品推荐
相关产品推荐

