LoginSignup
0
1

More than 3 years have passed since last update.

React-Redux 私的まとめ

Posted at

こちらの記事は以下の書籍を参考にアウトプットとして執筆しました。
React入門 React・Reduxの導入からサーバサイドレンダリングによるUXの向上まで

ルーティング

実行パターン

URL遷移なし

Store内にpageプロパティを実装するなどで判断

URLハッシュ

取得はlocation.hash
ハッシュが変更をきっかけにしている

history API

ブラウザの履歴情報を操作することができるAPIを使う手法

ルーティングライブラリ

react-router v4

API

history APIを使う

import { render } from '@testing-library/react';
import React from 'react';
import { Provider } from 'react-redux'
import { BrowserRouter as Router, Route } from 'react-router-dom'

// 略

render(
  <Provider store={store} >
    <Router>
      <Route path="/" component={App} />
    </Router>
  </Provider>,
  document.getElementByid('root')
)

引用:React入門 React・Reduxの導入からサーバサイドレンダリングによるUXの向上まで

BrowserRouterより下からRouteが使える

react-router-redux

react-routerを更にreduxに最適化できる
ルーティング情報をStoreのStateで管理

Reduxの非同期処理

redux-thunkによる非同期処理

ReduxではAPIからのレスポンスはActionとして扱う

thunkミドルウェア

ミドルウェア適応

import { createStore, applyMiddleware } from 'redux'
import logger from 'redux-logger'
import thunk from 'redux-thunk'
import reducers from './reducers'

const middlewares = [logger, thunk]

const store = createStore(reducers, applyMiddleware(...middlewares))
//createStoreの第2引数はStoreの初期オプションを与える

export default store

参考:React入門 React・Reduxの導入からサーバサイドレンダリングによるUXの向上まで

import shortid from 'shortid'
import * as types from '../types/todo'

// 同期Actionクリエータ
export function addTodo(title) {
  return {
    type: types.ADD_TODO,
    payload: {
      id: shortid.generate(),
      title,
    }
  }
}
// 非同期Actionクリエータ
// 関数をリターン
export function asyncAddTodo(title) {
  return (dispatch, getState) => {
    setTimeout(() => {
      dispatch(addTodo(title))
    }, 1000);
  }
}
0
1
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
1