iT邦幫忙

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

Zero to hero with React.js系列 第 27

【Day 27 React】Redux+API 製作 meme generator—— Part1

現在網路上有許多有趣的梗圖,今天我們不求人!就來串接 Imgflip API 取得梗圖,再透過讓使用者輸入要放在圖片上的文字,做出最客製化的梗圖~


環境建置

在專案的資料夾下,一樣 create react app

 $ create-react-app generator
 

建立完之後,我們需要安裝 reduxreact-reduxreact-bootstrapredux-thunk

$ npm install redux react-redux react-bootstrap redux-thunk --save

檔案節構

安裝完畢之後開啟專案,先把 src 資料夾清空,建立 index.js 並引入 reactreact-dom。並在 src 底下創建一個 component 資料夾,底下新增 App.js

src/index.js

import React from 'react';
import ReactDOM from 'react-dom';
import App from './component/App';

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

component/App.js

import React, { Component } from 'react';

class App extends Component {
  render(){
    return(
      <div>
        <h2> Welcome to the Meme Generator!</h2>
      </div>
    )
  }
}

export default App;


環境設定完畢


Fetch Memes Asynchronously

在串接 API 時需要登入帳號密碼,我們將這組帳好密碼包成一個 action。
先在 src 底下建立一個 actions 資料夾並新增 secrets.js

const username = 'AnnieTsai';
const password = '';

export { username, password };

但我們不想要在專案公開時,被其他瀏覽者看到我們的帳號密碼。
因此我們可以到 .gitignore 裡,將這個 action 的路徑寫上

./src/actions/secrets.js

action 資料夾底下建立 index.js,撰寫從 json 取得 memes 的邏輯

export const RECEIVE_MEMES = 'RECEIVE_MEMES';

function receiveMemes(json){
  const { memes } = json.data;

  return{
    type: RECEIVE_MEMES,
    memes
  }
}

我們可以透過 fetch 我們要的 API 來取得我們所需要的內容

Fetch API提供了一個JavaScript接口,用於訪問和操縱HTTP管道的部分,例如請求和響應。 它還提供了一個全局fetch()方法,該方法提供了一種簡單,合乎邏輯的方式來跨網絡異步獲取資源。

function fetchMemesJson(){
return fetch('https://api.imgflip.com/get_memes')
  .then(response => response.json())
}

export function fetchMemes(){
  return function(dispatch){
    return fetchMemesJson()
      .then(json => dispatch(receiveMemes(json)))
  }
}

套用 thunk middleware

建立 reducer 資料夾,並建立 index.js

import { combineReducer } from 'redux';
import { RECEIVE_MEMEs } form '../actions';

function memes(state = [], action){
  switch(action.type) {
    case RECEIVE_MEMES:
      return action.memes;
    default:
      return state;
  }
}

const rootReducer = combineReducer({memes});

export default rootReducer;

遇到一個 error,表示 action 必須為物件,我們要如何修正這個錯誤呢!

×
Error: Actions must be plain objects. Use custom middleware for async actions

import 剛剛沒有寫入的 thunk

import thunk from 'redux-thunk';

並在 store 套用

const store = createStore(rootReducer, applyMiddleware(thunk));

做到這邊,我們已經可以抓到 API 裡面的 100 物件囉


上一篇
【Day 26 React】Redux 做遊戲角色陣容應用程式——完結篇
下一篇
【Day 28 React】Redux+API 製作 meme generator—— Part2
系列文
Zero to hero with React.js30
圖片
  直播研討會
圖片
{{ item.channelVendor }} {{ item.webinarstarted }} |
{{ formatDate(item.duration) }}
直播中

尚未有邦友留言

立即登入留言