Categories: RxJS教程

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)加载数据。

编译时,显示如下:

terry

这个人很懒,什么都没有留下~

Share
Published by
terry

Recent Posts

自定义指令:聊聊vue中的自定义指令应用法则

今天我们来聊聊vue中的自定义…

6 天 ago

聊聊Vue中@click.stop和@click.prevent

一起来学下聊聊Vue中@cli…

2 周 ago

Nginx 基本操作:启动、停止、重启命令。

我们来学习Nginx基础操作:…

2 周 ago

Vue3:手动清理keep-alive组件缓存的方法

Vue3中手动清理keep-a…

3 周 ago

聊聊React和Vue组件更新的实现及区别

React 和 Vue 都是当…

4 周 ago