我目前正在开发一款智能家居类应用程序并且是初学者,我正在使用 mobX
设置事件房间名称。
我在“仪表板”组件中将它们设置为容器的标题。然后我想使用存储在里面的变量来过滤另一个名为“room”的组件中的房间。如果我对房间名称进行硬编码,它会起作用,但是当我用实际变量替换房间名称时,它会抛出一堆错误。
我已经尝试过在 componentWillUnmount()
中声明一些东西,但到目前为止还没有奏效。
这是我设置变量的地方
handleClick(e){
this.props.roomStore.room = e.target.closest('.btn__toggle').querySelector('.btn__headline').innerHTML;
}
这是我想要得到房间的地方
loadRooms(){
if(this.state.isLoaded){
var locations = this.state.things.filter( function (e){
return e.location == this.props.roomStore.room}); //<- this is the relevant variable
const habitems = locations.map((i, key) =>
<div className="btn__toggle" key={i.UID} type="submit">
<div className="btn__headline">{i.label}</div>
</div>
)
return habitems;
}
}
这是我渲染项目的地方:
render() {
if(this.state.isLoaded){
return (
<div>
<h1 id="h1">{this.props.roomStore.room}</h1>
<div className="btn__wrapper">{this.loadRooms()}</div>
</div>
);
}
我认为它可能不起作用,因为在您实际打开正确的组件之前,该变量已在另一个组件中设置,该组件在渲染中使用它,因此整个组件甚至在安装之前就已渲染。
但我在这一点上可能是错的。任何帮助将非常感激。 发生的错误是:
index.module.js:860 Uncaught TypeError: Cannot read property 'props' of undefined
The above error occurred in the component
Uncaught (in promise) TypeError: Cannot read property 'props' of undefined
react-dom.development.js:506 Warning: Can't perform a React state update on an unmounted component. This is a no-op, but it indicates a memory leak in your application. To fix, cancel all subscriptions and asynchronous tasks in the componentWillUnmount method.
最佳答案
您遇到的问题是您的过滤器函数无法访问this
,导致错误Cannot read property 'props' of undefined
。您可以使用 destructuring assignment 从 Prop 中过滤掉 roomStore
事先使用它而不是访问 this.props
。
loadRooms() {
const { roomStore } = this.props;
if (this.state.isLoaded) {
var locations = this.state.things.filter( function (e){
return e.location == roomStore.room
});
/* ... */
}
}
The destructuring assignment syntax is a JavaScript expression that makes it possible to unpack values from arrays, or properties from objects, into distinct variables.
关于javascript - 无法对未安装的组件执行 React 状态更新。这是一个空操作 - Mob X Related,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56044130/