美文网首页
20.redux使用

20.redux使用

作者: vbuer | 来源:发表于2018-09-03 16:10 被阅读8次

    react-redux

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

    先在入口文件内使用

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

    store

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

    • 把所有数据取出,如果是静态的就引入json文件,如果是动态的就使用fetch或者ajax加载,来自服务端的 state 可以在无需编写更多代码的情况下被序列化并注入到客户端中,在开发中使用本地的json数据可以加速开发
    • 然后使用redux库中的createStorereducer和上一步的数据实例化出一个store,eg:const store = createStore(rootReducer, defaultState);

    这样最简单的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
        }
    };
    

    相关文章

      网友评论

          本文标题:20.redux使用

          本文链接:https://www.haomeiwen.com/subject/nxxgiftx.html