RxJS:使用RxJS和ReactJS

在本章中,我们将看到如何将RxJ与ReactJS一起使用。我们不会在这里进入Reactjs的安装过程,要了解ReactJS的安装,请参考以下链接:/reactjs/reactjs_environment_setup.htm

我们将直接在下面的示例中工作,在该示例中,将使用RxJS中的Ajax加载数据。

index.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"));

index.html

<!DOCTYPE html>
<html>
   <head>
      <meta charset = "UTF-8" />
      <title>ReactJS Demo</title>
   <head>
   <body>
      <div id = "root"></div>
   </body>
</html>

我们使用了RxJS中的ajax,它将从此网址(https://jsonplaceholder.typicode.com/users)加载数据。

编译时,显示如下:

RxJS:使用RxJS和ReactJS

作者:terry,如若转载,请注明出处:https://www.web176.com/rxjs/1748.html

(0)
打赏 支付宝 支付宝 微信 微信
terryterry
上一篇 2021年2月4日 下午3:20
下一篇 2021年2月7日 下午9:50

相关推荐

发表回复

您的电子邮箱地址不会被公开。 必填项已用 * 标注