首页 > 解决方案 > 从非 react.component 类修改状态

问题描述

在我的文件中,我有一个Main扩展 React.Component 的类。该类在文件末尾导出。它有一些状态,其中之一是列表(Object[])。在该文件中有另一个类(我们称之为它Foo),它具有其他功能。我创建了对Foowithin的引用Main,然后使用它来调用bar()within Foo。在bar中,我有一个 for 循环,应该将 5 添加TestComponents到上面提到的列表中。由于它是一个状态,我也有Foo扩展React.Component. 问题是,即使这允许我使用setState(),组件也永远不会安装,所以当你修改你得到的状态时:

Warning: Can't call setState on a component that is not yet mounted. This is a no-op, but it might indicate a bug in your application. Instead, assign to `this.state` directly or define a `state = {};` class property with the desired state in the Foo component.

extends React.Component如果我从那时删除Foo当然,我不能改变状态,因为我不能使用setState. 这是我的主要代码的一个非常简化的版本:

interface State {
    list: Object[];
}

class Main extends React.Component<{}, State> {
    foo = new Foo();

    state = {
      list: [],
    }

  componentDidMount() {
    console.log(this.state.list); //logs: []

    this.foo.bar();

    console.log(this.state.list); //logs: [] expected: [TestComponent....]

  }

  render() {
    return (
      <IonContent>
          <IonList>
              {
                  //this.list.map(...);
              }
          </IonList>
      </IonContent>
    );
  };
};

class Foo extends React.Component<{}, State> {
    state = {
        list: [],
    } 
    
  constructor(props) {
    super(props);
   }

   componentDidMount() {
     console.log("mounted"); //doesnt log this since component doesnt get mounted
   }
   
  bar() {
    for(let i = 0; i < 5; i++) {
      let a = <TestComponent key={i}></TestComponent>
      
      this.setState({
        list: [...this.state.list, a], //errors here saying component not mounted
      });

    }
  }
}
export default Main;

我如何list从内部修改状态,Foo因为Foo从未作为组件安装(从未记录“已安装”)?我尝试查看渲染功能是否会安装它,但就像我认为它没有一样。

render() {
      return(
          <></>
      );
  }

标签: reactjsionic-frameworkreact-component

解决方案


我使用全局变量让它工作(这应该同时解决两个问题。我需要在单个脚本中但在每个脚本中都需要数组“全局”)

我通过创建一个 globals.tsx 文件来做到这一点。在我添加的文件中:

export var bluetoothDevices: Object[] = [];

然后访问它你可以做的全局:

import { bluetoothDevices }  from '/globals/globals'

bluetoothDevices.push(x);

它就像将任何东西推送到数组一样简单。我可以确认它在文件中有效(我可以修改并从每个类中读取它)虽然我无法确认它是否适用于所有脚本,因为我目前只有一页。


推荐阅读