項目地址:https://github.com/xiaoyuqing/react-redux-instagram,喜歡的話動動手指點點贊^-^ 1.初始化項目 IndexRoute是預設路由 2.增加store文件 const history = syncHistoryWithStore(brows ...
項目地址:https://github.com/xiaoyuqing/react-redux-instagram,喜歡的話動動手指點點贊^-^
1.初始化項目
IndexRoute是預設路由
2.增加store文件
const history = syncHistoryWithStore(browserHistory, store)
用syncHistoryWithStore是為了讓react-router 的 history 跟 store 互相同步
3.增加action文件
包括增加❤️,增加評論,刪除評論
4.增加reducer文件
combineReducers 把一個由多個不同 reducer 函數作為 value 的 object,合併成一個最終的 reducer 函數,然後就可以對這個 reducer 調用 createStore 方法。
為了讓router與redux保持一致,要把routeReducer加進來,必須是routing,不是routing會報錯。
const rootReducer = combineReducers({posts, comments, routing: routerReducer });
5.把Provider引進來,把store傳給provider,history傳給router
<Provider store={store}>
<Router history={history}>
</Router>
</Provider>
6.創建一個app組件,編寫mapStateToProps,mapDispachToProps,用connect把組件跟store連接起來,用bindActionCreators結合actionCreators跟dispatch,把 action creator 往下傳到一個組件
const App = connect(mapStateToProps, mapDispachToProps)(Main);
7.接下來創建photo組件,把photo組件傳給photoGrid,主頁已經創建好了。修改post的reducer,點❤️的時候增加like數,還有動效
// post reducer
function posts(state = [], action) {
switch(action.type) {
case 'INCREMENT_LIKES' :
console.log("Incrementing Likes!!");
const i = action.index;
return [
...state.slice(0,i), // before the one we are updating
{...state[i], likes: state[i].likes + 1},
...state.slice(i + 1), // after the one we are updating
]
default:
return state;
}
}
8.接下來創建comments組件,comments可以增加評論跟刪除評論,在single裡面引入comments跟photo,增加comments的reducer,詳情頁就建好了
function postComments(state = [], action) {
switch(action.type){
case 'ADD_COMMENT':
// return the new state with the new comment
return [...state,{
user: action.author,
text: action.comment
}];
case 'REMOVE_COMMENT':
// we need to return the new state without the deleted comment
return [
// from the start to the one we want to delete
...state.slice(0,action.i),
// after the deleted one, to the end
...state.slice(action.i + 1)
]
default:
return state;
}
return state;
}
總結
一個項目做下來,對redux跟react-redux的使用更加熟悉了,發現redux對於組件間的數據管理真的是很有效果的
github地址:https://github.com/xiaoyuqing/react-redux-instagram, 喜歡的話動動手指點點贊^-^