javascript - Undefined 不仅仅是我的构造函数中某些变量的对象
问题描述
我有一个非常简单的问题,但我无法弄清楚它为什么会发生。我有一个组件,我在构造函数中声明了两个数组:
class FilterModal extends Component {
constructor(props) {
super(props);
this.transport_options = ["driving", "tram", "walking"];
this.pressed_percentages = ["allPressed", "under15Pressed","under30Pressed", "over30Pressed"];
filters = {
"driving": {
"allPressed":false,
"under15Pressed":false,
"under30Pressed":false,
"over30Pressed":false
},
"tram": {
"allPressed":false,
"under15Pressed":false,
"under30Pressed":false,
"over30Pressed":false
},
"walking": {
"allPressed":false,
"under15Pressed":false,
"under30Pressed":false,
"over30Pressed":false
},
"isFilterActive": false
}
//state declared here
}
}
我想访问变量transport_options
和pressed_percentages
我在构造函数之后定义的函数:
resetPressed = () => {
this.transport_options.forEach(function (transport_option) {
this.pressed_percentages.forEach(function (pressed_percentage) {
filters[transport_option][pressed_percentage] = false;
})
});
//additional business logic
}
我的问题是:当我打电话时resetPressed
,我收到了消息"undefined is not an object (evaluating 'this.pressed_percentages')
。但是,this.transport_options
不会触发任何错误消息。
所以我的问题是:为什么this.transport_options
有效,但this.pressed_percentages
会引发错误?
解决方案
这一定是您的功能未绑定的问题。尝试使用箭头运算符来定义您的函数或使用bind
以下示例中使用的函数。
class App extends React.Component {
constructor(props) {
super(props);
this.transport_options = ["driving", "tram", "walking"];
this.pressed_percentages = ["allPressed", "under15Pressed","under30Pressed", "over30Pressed"];
this.filters = {
"driving": {
"allPressed":false,
"under15Pressed":false,
"under30Pressed":false,
"over30Pressed":false
},
"tram": {
"allPressed":false,
"under15Pressed":false,
"under30Pressed":false,
"over30Pressed":false
},
"walking": {
"allPressed":false,
"under15Pressed":false,
"under30Pressed":false,
"over30Pressed":false
},
"isFilterActive": false
}
// This binding is necessary to make `this` work in the callback
this.handleClick = this.handleClick.bind(this);
}
handleClick() {
console.log(this.transport_options)
}
render() {
return (
<button onClick={this.handleClick}>
click me
</button>
);
}
}
ReactDOM.render(
<App />,
document.getElementById('root')
);
在回调中,您还必须像这样绑定您的函数。
resetPressed = () => {
this.transport_options.forEach((transport_option)=> {
this.pressed_percentages.forEach((pressed_percentage) =>{
this.filters[transport_option][pressed_percentage] = false;
})
});
//additional business logic
}
更多解释请参考事件处理反应
推荐阅读
- mysql - MariaDB 10.1.44 没有 row_number() 的行数
- conan - 如何修改/影响/调整柯南依赖项
- javascript - 如何在 div JavaScript 上创建上下文菜单?
- c++ - 删除从 Tcl_NewListObj 返回的 tcl 列表
- android - 单击 android 模拟器上的按钮时,flutter-webrts 视频通话应用程序崩溃,并且相机显示奇怪的图像
- testing - 有条件地忽略 JUnit5 中的测试的正确方法?
- javascript - 未找到模块:无法解析“
- sql - 这种对左连接的解释有意义吗?
- forms - 基于 Symfony 事件的 Symfony 更新表单字段
- javascript - React Redux 按钮调度问题