
使用 RxJS 和 ReactJS
在本章中,我們將介紹如何將 RxJS 與 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,該 ajax 將從該 URL 載入資料: https://jsonplaceholder.typicode.com/users。
編譯後,顯示如下所示:-

廣告