使用 RxJS 和 ReactJS
在本章中,我们将了解如何将 RxJs 与 ReactJS 结合使用。这里我们不会进入Reactjs的安装过程,要了解ReactJS安装请参考这个链接:/reactjs/reactjs_environment_setup.htm
例子
我们将直接使用下面的示例,其中将使用 RxJS 中的 Ajax 来加载数据。
索引.js
import React, { Component } from "react";
import ReactDOM from "react-dom";
import { ajax } from 'rxjs/ajax';
import { map } from 'rxjs/operators';
class App extends Component {
constructor() {
super();
this.state = { data: [] };
}
componentDidMount() {
const response = ajax('https://jsonplaceholder.typicode.com/users').pipe(map(e => e.response));
response.subscribe(res => {
this.setState({ data: res });
});
}
render() {
return (
<div>
<h3>Using RxJS with ReactJS</h3>
<ul>
{this.state.data.map(el => (
<li>
{el.id}: {el.name}
</li>
))}
</ul>
</div>
);
}
}
ReactDOM.render(<App />, document.getElementById("root"));
索引.html
<!DOCTYPE html>
<html>
<head>
<meta charset = "UTF-8" />
<title>ReactJS Demo</title>
<head>
<body>
<div id = "root"></div>
</body>
</html>
我们使用 RxJS 中的 ajax 来从此 Url 加载数据 - https://jsonplaceholder.typicode.com/users。
编译时,显示如下 -
