reactjs - 从非 react.component 类修改状态
问题描述
在我的文件中,我有一个Main
扩展 React.Component 的类。该类在文件末尾导出。它有一些状态,其中之一是列表(Object[])。在该文件中有另一个类(我们称之为它Foo
),它具有其他功能。我创建了对Foo
within的引用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(
<></>
);
}
解决方案
我使用全局变量让它工作(这应该同时解决两个问题。我需要在单个脚本中但在每个脚本中都需要数组“全局”)
我通过创建一个 globals.tsx 文件来做到这一点。在我添加的文件中:
export var bluetoothDevices: Object[] = [];
然后访问它你可以做的全局:
import { bluetoothDevices } from '/globals/globals'
bluetoothDevices.push(x);
它就像将任何东西推送到数组一样简单。我可以确认它在文件中有效(我可以修改并从每个类中读取它)虽然我无法确认它是否适用于所有脚本,因为我目前只有一页。
推荐阅读
- azure - 使用 Azure 策略拒绝 Azure 磁盘加密解密/禁用
- javascript - 使用 Props Callback 和 react native
- rest - 仅当提供 Web API 密钥名称时才能指定 Web API 密钥
- autodesk-forge - 查看器版本 7 中的 WebGL GL_INVALID_OPERATION
- python - Python,展平丑陋的嵌套 for 循环
- php - 如何将 XML 写入 CSV 格式
- google-cloud-platform - 如何编辑谷歌云虚拟机实例?
- android - 如何在自定义通知中添加自定义视图?
- flutter - 在构建方法中没有的小部件中使用按钮的回调函数
- julia - 如何在 Julia 中读取(二进制)文件的最后 x 个字节?