iT邦幫忙

2017 iT 邦幫忙鐵人賽
DAY 23
0
Modern Web

RRRR的世界 (Ruby on Rails + React + Redux)系列 第 23

Day 23, Redux 一樣先玩範例!

  • 分享至 

  • xImage
  •  

前置作業:

  1. 安裝react-devtool
  2. git clone https://github.com/reactjs/redux/
  3. 照著 指令

好,要使用react devtool之前,要先做一些設定:

redux/src/index.js
//原本:const store = createStore(reducer)

const store = createStore(reducer, window.__REDUX_DEVTOOLS_EXTENSION__ && window.__REDUX_DEVTOOLS_EXTENSION__());

接著 npm start

http://ithelp.ithome.com.tw/upload/images/20170108/20103835yIb26l0A0b.png

http://ithelp.ithome.com.tw/upload/images/20170108/20103835RKuQ8tY0nQ.png

redux tab就會看到每個action及state的改變。
但是要注意,如果是server render的話要做比較多改變,因為window會給你報錯誤,會一直run不起來...
(這也是我今天de很久的原因)

action的部分對應到 code:

let nextTodoId = 0
export const addTodo = (text) => ({
  type: 'ADD_TODO',
  id: nextTodoId++,
  text
})

export const setVisibilityFilter = (filter) => ({
  type: 'SET_VISIBILITY_FILTER',
  filter
})

export const toggleTodo = (id) => ({
  type: 'TOGGLE_TODO',
  id
})    

state變化的部分也可以看到reducercontainer裡的dispatch

有趣的是你可以注意到兩種mapDispatchToProps的寫法:

//  src/containers/FilterLink.js
//  pass into function
const mapDispatchToProps = (dispatch, ownProps) => ({
  onClick: () => {
    dispatch(setVisibilityFilter(ownProps.filter))
  }
})

//  src/containers/VisibleTodoList.js
//  pass into object
const mapDispatchToProps =  ({
  onTodoClick: toggleTodo
})

是不是缺少了dispatch?別慌!https://github.com/reactjs/react-redux/blob/master/docs/api.md#connectmapstatetoprops-mapdispatchtoprops-mergeprops-options

[mapDispatchToProps(dispatch, [ownProps]): dispatchProps] (Object or Function):

  • If an object is passed, each function inside it will be assumed to be a Redux action creator. An object with the same function names, but with every action creator wrapped into a dispatch call so they may be invoked directly, will be merged into the component’s props
    If a function is passed, it will be given dispatch. It’s up to you to return an object that somehow uses dispatch to bind action creators in your own way.

如次一來,我也把example跑完了!
明天要來把東西搬進action, store, reducer了!!


上一篇
Day 22, Redux - 先理解一下
下一篇
Day 24, Redux Action / ActionCreator 根本是歸納法
系列文
RRRR的世界 (Ruby on Rails + React + Redux)30
圖片
  直播研討會
圖片
{{ item.channelVendor }} {{ item.webinarstarted }} |
{{ formatDate(item.duration) }}
直播中

尚未有邦友留言

立即登入留言