前置作業:
好,要使用react devtool之前,要先做一些設定:
redux/src/index.js
//原本:const store = createStore(reducer)
const store = createStore(reducer, window.__REDUX_DEVTOOLS_EXTENSION__ && window.__REDUX_DEVTOOLS_EXTENSION__());
接著 npm start
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變化的部分也可以看到reducer與container裡的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了!!