Warning: file_get_contents(/data/phpspider/zhask/data//catemap/3/reactjs/21.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181

Warning: file_get_contents(/data/phpspider/zhask/data//catemap/3/html/73.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Reactjs 如何在React应用程序中使用BehaviorSubject_Reactjs_Rxjs_Behaviorsubject - Fatal编程技术网

Reactjs 如何在React应用程序中使用BehaviorSubject

Reactjs 如何在React应用程序中使用BehaviorSubject,reactjs,rxjs,behaviorsubject,Reactjs,Rxjs,Behaviorsubject,我的主应用程序(非react)具有BehaviorSubject数据对象。用户单击一个按钮,就可以在子浏览器窗口中打开应用程序的响应端 应用程序的react端有一个组件,该组件获取数据并使用数据创建表 在子窗口中,我可以转到我的调试器并执行以下操作,以查看console中的主题值更改 window.opener.app.varCollection$.subscribe({ next: (v) => console.log(JSON.stringify(v)) }); 如何将此数据提供

我的主应用程序(非react)具有BehaviorSubject数据对象。用户单击一个按钮,就可以在子浏览器窗口中打开应用程序的响应端

应用程序的react端有一个组件,该组件获取数据并使用数据创建表

在子窗口中,我可以转到我的调试器并执行以下操作,以查看console中的主题值更改

window.opener.app.varCollection$.subscribe({
  next: (v) => console.log(JSON.stringify(v))
});
如何将此数据提供给下面的react组件?我不确定订阅在React端将如何工作

<DataPanel jsonData={this.state.sysvarData} ></DataPanel>

您可以在组件本身或其父组件上执行此操作,并将值作为道具传递给它

只需订阅componentDidMount事件上的可观察内容:

componentDidMount() {
   window.opener.app.varCollection$.subscribe(val => this.setState({value:val}))
}

一个好的做法是使用TakeTill操作符和主题处理组件WillUnmount事件上的取消订阅:

unmount$ = new Subject() //component class property

componentDidMount() {
   //if using rxjs 6:
   window.opener.app.varCollection$
     .pipe(takeUntil(this.unmount$)) 
     .subscribe(val => this.setState({value:val}))
   //if using rxjs 4 or 5:
   window.opener.app.varCollection$
     .takeUntil(this.unmount$)
     .subscribe(val => this.setState({value:val}))
}

componentWillUnmount() {
   this.unmount$.next(true)
}

render() {
   const {value} = this.state //now you have the value on the render funtion
   ...
}

订阅componentDidMount对我不起作用。状态变量没有更新。我不确定可能是什么问题。它在这里工作,但只使用来自同一http服务器的两个文件。另一个解决方案是在父窗口上使用postMessage,并在子窗口上侦听“message”事件。我将postMessage用作备份。当我将订阅和设置状态放入组件构造函数时,它就工作了。谢谢你的建议。