iT邦幫忙

2018 iT 邦幫忙鐵人賽
DAY 18
0
Modern Web

30天React從入門到入坑系列 第 18

DAY18:ajax fatch & react-axios

react使用ajax可以選用fetch API或react-axios,react-axios是把axios在包裝成components,所以可直接使用標籤方式呼叫ajax,但安裝使需注意dependancies。fetch API或直接使用axios,呼叫時注意react生命周期。

使用Fetch
https://developer.mozilla.org/zh-CN/docs/Web/API/Fetch_API/Using_Fetch

src/Fetch.js

import React, { Component } from 'react';

class Fetch extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      rsobj: {},
      isLoaded: false,
      error: null
    };
  }

  componentDidMount() {
    fetch("https://httpbin.org/get")
      .then(res => res.json())
      .then((result) => {
          this.setState({
            isLoaded: true,
            rsobj: result
          });
        },(error) => {
          this.setState({
            isLoaded: true,
            error: error
          });
        }
      )
  }

  render() {
    const { isLoaded, error, rsobj } = this.state;
    if (error) {
      return <div>Error: {error.message}</div>;
    } else if (!isLoaded) {
      return <div>Loading...</div>;
    } else {
      return (
        <p>{JSON.stringify(rsobj)}</p>
      );
    }
  }
}

export default Fetch;

react-axios
除了安裝react-axios,還需安裝依懶的axios與prop-types,照著文件安裝即可。
https://www.npmjs.com/package/react-axios

src/Axios.js

import React, { Component } from 'react';
import { Get } from 'react-axios';

class Axios extends React.Component {
  constructor(props) {
    super(props);
  }

  render() {
    return (
      <div>
        <Get url="https://httpbin.org/get" >
          {(error, response, isLoading, onReload) => {
            if(error) {
              return (<div>Something bad happened: {error.message} <button onClick={() => onReload({ params: { reload: true } })}>Retry</button></div>)
            }
            else if(isLoading) {
              return (<div>Loading...</div>)
            }
            else if(response !== null) {
              return (<div>{JSON.stringify(response)} <br/> <button onClick={() => onReload({ params: { refresh: true } })}>Refresh</button></div>)
            }
            return (<div>Default message before request is made.</div>)
          }}
        </Get>
      </div>
    )
  }
}

export default Axios;
src/index.js

import React from 'react';
import ReactDOM from 'react-dom';
import Axios from './Axios';
import Fetch from './Fetch';
import registerServiceWorker from './registerServiceWorker';

const App = () => (
  <div>
    <h1>Fetch</h1>
    <Fetch />
    <h1>Axios</h1>
    <Axios />
  </div>
)

ReactDOM.render(
  <App />,
  document.getElementById('root'));
registerServiceWorker();

輸出畫面
https://ithelp.ithome.com.tw/upload/images/20180105/201073176XSYAk0i6j.png

參考資料:
use axios fetch data
https://daveceddia.com/ajax-requests-in-react/


上一篇
DAY17:React state 同步,非同步??
下一篇
DAY19:React Webpack say Hello(設定檔)
系列文
30天React從入門到入坑30

尚未有邦友留言

立即登入留言