掌握React - Redux,一点就透!

20,291 阅读2分钟

大家好,我是右子。

前言

Redux它是一个有用的架构,但并不是非用不可。在开发时的大多数情况下,你是可以不用它。如果你不希望你的项目更复杂,就别用redux(好矛盾...)。

首先,vuex作为状态管理模式的设计模式,被后来国内的技术小伙伴们喜爱,相信一些先用过vuex的小伙伴,再用redux,一定会有一些吐槽。

两者的框架在设计模式是不一样的,自然基于他们本身建设的生态也是不一样的。

放下偏见,今天我们一起看一下Redux的入门学习和使用。

工作流

了解之前我们先看一下它的工作流程

image.png

依赖安装

npm i redux react-redux -S

背单词

我喜欢在正式实践之前前,把关键api背下来,因为这样会方便你后期很好的编程使用,不必一次次去查。

Redux JavaScript API:

  • combineReduces
  • createStore

React-Redux JavaScript API:

  • connect
  • Provider

你没看错,你先学会“这点儿”就够你用了。

在工程中的应用内

像使用vuex一样,你会创建一个stores文件夹,react项目你需要创建一个reduces文件夹。(规范你们懂的)

  • 创建reduces/index.js文件
// path:reduces/index.js

import {combineReducers} from 'redux';
import reduxStateStore from './stores';

export default combineReducers({
    storex
});
  • 创建reduces/stores.js文件,规则是:
    • 接受参数,并返回一个新的state。
    • 通过action的type不同,返回新的state,不能直接修改state。
// path:reduces/stores.js

// 状态
const stateStore = {
    websiteTitle: "Hello Redux"
};
const types = {
    "setWebsiteTitle":function(data){
        if(typeof data !== 'object'){
            throw Error('参数必须是object类型');
        }
        stateStore['websiteTitle'] = data.value;
    }
};
// 这个就是reducers!
export default (state=stateStore, action)=>{
    let actionType = action.type;
    // 使用策略模式,更好的操作你的Types。
    types[actionType] && types[actionType](action.payload);
    return state;
};
  • 创建app.jsx组件
import React from 'react';
import {connect} from 'react-redux';

class ReactApp extends React.Component{
    contructor(props={}){
        super(props);
    }
    handlerTitle(){
        this.props.modifyTitle();
    }
    render(){
        let store = this.props;
        return (
            <div className="ReactAppWrapper">
                Hello React Redux.
                {{store.title}}
                <button onClick={this.handlerTitle}></button>
            </div>
        );
    }
};
// 利用connect将组件关联起来
export default connect({
    ({storex}):()=>{
        title: storex.websiteTitle
    },
    (dispatch):()=>{
        modifyTitle(){
            dispatch({
                type: 'setWebsiteTitle',
                payload: {
                    value: 'hello react redux!'
                }
            });
        }
    }
})(ReactApp);
  • 创建主文件main.js文件
import React from 'react';
import ReactDOM from 'react-dom';
import {createStore} from 'react';
import {Provider} from 'react-redux';
import reduces from './reduces/index';
import App from './app.js';

const STORES = createStore(reduces);

ReactDOM.render(
    <Provider store={STORES}>
        <App />
    </Provider>
);

相关文档

阮一峰老师的Redux入门教程