项目地址: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, 喜欢的话动动手指点点赞^-^