iT邦幫忙

5

[TaichungBike] 公共腳踏車租借查詢 - React

TaichungBike

這個專案主要是用來練習React串接API,目的是要做一個各縣市公共腳踏車租借情況的立即查詢應用,往後會持續改善成一個Product。

程式碼:https://github.com/Luis-Chen/TaichungBike


結構

/**
 * App 結構
 * - 用axios()從API撈取資料
 * - 設定<select>與<option value>
 *   參考資料:https://reactjs.org/docs/forms.html#the-select-tag
 * - 送出表單後依據<option value>更換城市的API
 * - 使用map()列出資料
 */

constructor()

先設定this.state.city 預設值為"Taoyuan"桃園 跟 information:[] 之後API撈到的資料會存在這裡
下面兩個是From表單 與 <select> 選單的設定 可以參考React Doc

  • this.handleChange = this.handleChange.bind(this);
  • this.handleSubmit = this.handleSubmit.bind(this);
  constructor(props) {
    super(props);
    this.state = {
      city: "Taoyuan",
      information: []
    };

    this.handleChange = this.handleChange.bind(this);
    this.handleSubmit = this.handleSubmit.bind(this);
  }

handleChange()

允許 <select>更換縣市選項<option value>

**!!注意!!**React 都要寫function才能修改或更換表單內容 不然是不能動的
像是 <input value="Hello"> 想說是不是能直接改,其實會發現不能刪除Hello的字串

  handleChange(event) {
    this.setState({ city: event.target.value });
  }

handleSubmit()

表單送出後要執行的動作,alert() 是要確認<select>是否有更換縣市,並且顯示我們要連接的API網址是否正確。
順便玩玩swagger

API Url 的格式:
http://ptx.transportdata.tw/MOTC/v2/Bike/Availability/{City}
{City}我們用 ${this.state.city} 去替換 this.state.city 就是從<select>去更換

如果有去看過React Doc會發現我只是將再加上API的串接而已,我用axios之前是用fetch

axios

這邊要注意一個點 就是要在response後面加上data
你可以用console.log(response)測試看看

下面那邊文件可以參考一下 為什麼會用axios
Why do I stop using Fetch? (and what are the alternative options?)

    handleSubmit(event) {
    alert(
      "Your favorite flavor is: " +
        `http://ptx.transportdata.tw/MOTC/v2/Bike/Availability/${this.state.city}`
    );
    event.preventDefault();
    axios
      .get(
        `http://ptx.transportdata.tw/MOTC/v2/Bike/Availability/${this.state.city}`
      )
      .then(response => {
        console.log(response);
        this.setState({ information: response.data });

        console.log(this.state.information);
      })
      .catch(error => {
        console.log(error);
      });
    
    }

from

送出表單用onSubmit
想要更換<option>onChange
value就是 記錄選好的選項

    <form onSubmit={this.handleSubmit}>
      <select value={this.state.city} onChange={this.handleChange}>
        <option value="Taipei">台北市</option>
        <option value="NewTaipei">新北市</option>
        <option value="Taoyuan">桃園市</option>
        <option value="Taichung">台中市</option>
      </select>
      <br />
      <input type="submit" value="送出" />
    </form>

Table

顯示資訊,用map()
**!!注意**
有時會出現像是 TypeError: this.state.information.map is not a function
或是TypeError: Cannot read property 'setState' of undefined 其實只是回傳資料時格式不對,多用console.log()

    <tbody>
    {this.state.information.map((list, index) => (
      <tr>
        <td>{list.StationUID}</td>
        <td>{list.StationID}</td>
        <td>{list.ServieAvailable}</td>
        <td>{list.AvailableRentBikes}</td>
        <td>{list.AvailableReturnBikes}</td>
        <td>{list.UpdateTime}</td>
      </tr>
    ))}
    </tbody>

結語

好久沒已發文了,偶而上線還會看到時有大大還會按我追蹤> <真的很不好意思明明沒什麼料,所以我想說應該要多發點文惹,不然有點愧對有追蹤我的大大。
從我年初的鐵人賽的發文是我學程式的開始,從很爛的PHP義大利麵程式碼到改用node.js到現在初學React,現在回頭,發現這幾個月來我也成長了不少,現在剛好React有更新過,很多打法幾乎都是要重學了,而且台灣在React相關的文章其實還算少數,想說我也應該貢獻一點我的學習心得,總之感謝各位大大了


圖片
  直播研討會
圖片
{{ item.channelVendor }} {{ item.webinarstarted }} |
{{ formatDate(item.duration) }}
直播中

1 則留言

0
海綿寶寶
iT邦大神 1 級 ‧ 2017-10-29 13:35:12

好分享,按三個讚
/images/emoticon/emoticon12.gif/images/emoticon/emoticon12.gif/images/emoticon/emoticon12.gif

另外請教一下
這個程式跟官網的 javascript 範例的差別

1.官網用 jQuery;您用的是 React
2.官網只抓「資料」;您還有設計「UI」(可選擇城市)
還有其他的差別嗎?

Luis-Chen iT邦新手 4 級 ‧ 2017-10-29 16:07:05 檢舉

我是邊做邊想,有些欄位是要跟別的API連動才能撈出有用的資料 像是如何用StationID(站點代碼)欄位 找出另一個API/v2/Bike/Station/{City}的公共自行車租借站位資料,往後應該會加上地圖跟即時更新查詢的功能

了解了
/images/emoticon/emoticon41.gif

我要留言

立即登入留言