React嵌套函数中Props访问失效问题求助
解决React嵌套函数中this.props访问失败的问题
你遇到的问题是普通函数的this绑定规则导致的:外层onBeforeSend里的this指向React组件实例,但嵌套的args.ajaxSettings.beforeSend是普通函数,它的this会被绑定到调用它的上下文(而非组件实例),所以this.props会是undefined,自然读不到team_id。
下面是三种可行的解决方案:
方案1:使用箭头函数
箭头函数不会创建自己的this,会继承外层作用域的this,直接替换嵌套函数为箭头函数即可:
onBeforeSend(args) { console.log(this.props.team_id); args.ajaxSettings.beforeSend = (args) => { // 箭头函数继承外层的this,指向组件实例 console.log(this.props.team_id); args.httpRequest.setRequestHeader('Authorization', 'public/'); }; }
方案2:提前保存组件的this到变量
在onBeforeSend里先把组件的this存到一个变量(比如that/self),嵌套函数里用这个变量访问props:
onBeforeSend(args) { console.log(this.props.team_id); const that = this; // 保存组件实例的this args.ajaxSettings.beforeSend = function (args) { console.log(that.props.team_id); // 用that访问组件的props args.httpRequest.setRequestHeader('Authorization', 'public/'); }; }
方案3:用bind绑定组件的this
把嵌套函数的this绑定为组件实例,确保它能访问到this.props:
onBeforeSend(args) { console.log(this.props.team_id); args.ajaxSettings.beforeSend = function (args) { console.log(this.props.team_id); args.httpRequest.setRequestHeader('Authorization', 'public/'); }.bind(this); // 绑定组件的this到这个函数 }
内容的提问来源于stack exchange,提问作者marcorivera8
相关产品推荐
相关产品推荐

