20.redux使用

2018-09-03  本文已影响8人  vbuer

react-redux

使用一个react-redux 的库使得redux的使用更简洁,它提供了providerconnect方法

先在入口文件内使用

<Provider store={store}>
     <组件/>  
</provider>

store

这里使用了redux中的重要组成部分store,所以下面先说store的文件构成

这样最简单的store就做好了,然后上面还有reducer需要处理


reducer

reducer的简单作用就是根据action的不同跟新state,此处的更新必须是返回一个新的state,而不是在原来的state上做修改

例如:实现一个增加评论和删除评论的功能

//注意此处传的参为state和action
let postComments = (state = [], action) => {
    switch (action.type){
        case "ADD_COMMENT":
            return [
                ...state, //原来的state
                {
                    user: action.author,增加的state
                    text: action.text
                }
            ];
        case "REMOVE_COMMENT":
            return [
                ...state.slice(0,action.i),  //剔除数组中需要删除的那个
                ...state.slice(action.i + 1)
            ];
        default:
            return state;
    }
};

在我们的项目中,我们可能会分模块和功能写多个reducer文件,但最终,我们都需要把它合并到一个里面,这需要使用redex中的combineReducers

import { combineReducers } from "redux";
import * as reducers from "./reducers"
const rootReducer = combineReducers({
    ...reducers
});
export default rootReducer;

这是通用的用法,而在我学习的视频中,他在combineReducers中还加上了routerReducer,它的具体作用可以看官方文档react-router-redux,反正我是没怎么看懂,具体的作用感觉就是在切换页面的时候会多出一个LOCATION_CHANGE的时间,可以用来追踪页面的变化,具体要使用的话需要更改3个文件,

  1. 上面的合并reducers的文件,在引入react-router-redux库的routerReducer方法后,在combineReducers中加上routing: routerReducer
  2. 在store.js中加上以下代码
...
import { syncHistoryWithStore } from 'react-router-redux';
import { browserHistory } from 'react-router';
...
export const history = syncHistoryWithStore(browserHistory, store);

3.在主入口文件中的<Router>根路由标签使用store.js中导出的history

<Router history={history}>
...
<Router>

action

action我把它做是一个接口,它主要是和reducer联动的,它默认必须返回一个type,用这个type的值来判断reducer中做哪一步操作
例如:我需要增加一个评论,那我需要传评论文章的id,评论的用户,评论的内容,所以定义如下

// add comment
export let addComment = (postId, author, text) => {
    return {
        type: 'ADD_COMMENT',
        postId,
        author,
        text
    }
};
上一篇下一篇

猜你喜欢

热点阅读