React中setState传入自定义类调用时报this.setState读取错误
问题原因
这是JavaScript类方法的this绑定丢失导致的错误。
ES6类的方法默认挂在原型上,当你执行const updateBtn = btnManager.updateBtn把方法从实例上单独拆出来赋值给变量后,再调用updateBtn()时,方法内部的this会丢失原本的实例指向:React运行在严格模式下,此时函数内的this为undefined,访问this.setState自然会抛出属性不存在的错误。
构造函数里打印能正常看到setState,是因为构造函数执行时this确实指向当前创建的实例,和后续方法被单独调用时的上下文无关。
可行解决方法
你可以根据自己的编码习惯选任意一种:
- 直接通过实例调用方法,不拆分方法引用
不要把updateBtn单独赋值给变量,始终通过btnManager实例调用,就能保留正确的this指向:useEffect(() => { const btnManager = new BtnManager(setBtnProps); if (!accountId) { btnManager.updateBtn(); } else if (!tokenOut.info) { btnManager.updateBtn('Select a Pool', true); } }, [accountId, tokenOut.info]) - 提取方法时手动绑定this上下文
如果确实需要把方法提取为独立变量,赋值时用bind绑定实例作为this:const updateBtn = btnManager.updateBtn.bind(btnManager); - 构造函数内提前绑定方法this
在BtnManager的构造函数里固定绑定updateBtn的this,后续不管怎么拆分调用都不会丢失上下文:constructor(setState: React.Dispatch<React.SetStateAction<IBtnProps>>) { this.setState = setState; this.updateBtn = this.updateBtn.bind(this); } - 用类箭头函数属性定义方法
箭头函数没有自己的this,会继承定义时外层作用域的this(也就是类实例),改写updateBtn为箭头函数形式即可避免绑定问题:public updateBtn = (text?: string, disabled?: boolean, rest?: IBtnProps) => { if (!rest) rest = INITIAL_BUTTON_STATE; if (text && disabled) { this.setState({ ...rest, text, disabled, }); } else { this.setState(rest); } }
内容的提问来源于stack exchange,提问作者keithfrazier98
相关产品推荐
相关产品推荐

