javascript - 无法对未安装的组件执行 React 状态更新。这是一个空操作 - Mob X Related

标签 javascript reactjs react-router mobx-react

我目前正在开发一款智能家居类应用程序并且是初学者,我正在使用 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/

相关文章:

reactjs - 未捕获的 TypeError : (0 , _reactRedux.bindActionCreators) 不是一个函数

javascript - react axios 401未经授权

javascript - 根据深度嵌套数组的项目有条件地渲染组件

reactjs - react : Cannot Login if url entered manually into the browser

reactjs - react 。您不应在 <Router> 之外使用 <withRouter(App)/>

javascript - 用 sinon stub 非导出函数

javascript - 在react bootstrap中编辑时在选择字段中显示变量的内容

javascript - 首次打开 IE 后 Bootstrap Carousel 停止工作

javascript - 如何在 KnockoutJS 中用 {{}} 样式绑定(bind)替换 data-bind 标签?

reactjs - 使用 React Router 锚定选项卡