Redux入门到使用

欢迎关注公众号:n平方
若有问题或建议,请后台留言,我会尽力解决你的问题。

简介

Redux是针对JavaScript应用的可预测状态容器。html

若是熟悉设计模式之观察者模式理解起来就简单了。就是将你在其余组件中须要用到的数据放到一个容器中,那么组件就能够从其中取放数据的东西就是redux的工做。

特性:react

  • 可预测性(predictable): 由于Redux用了reducer与纯函数(pure function)的概念,每一个新的state都会由旧的state建来一个全新的state。于是全部的状态修改都是”可预测的”。
  • 状态容器(state container): state是集中在单一个对象树状结构下的单一store,store便是应用程序领域(app domain)的状态集合。
  • JavaScript应用: 这说明Redux并非单指设计给React用的,它是独立的一个函数库,可通用于各类JavaScript应用。

核心概念

action:是把数据从应用(译者注:这里之因此不叫 view 是由于这些数据有多是服务器响应,用户输入或其它非 view 的数据 )传到 store 的有效载荷。它是 store 数据的惟一来源。通常来讲你会经过 store.dispatch() 将 action 传到 store。git

reducer:指定了应用状态的变化如何响应 actions,并发送到 store 的,记住 actions 只是描述了有事情发生了这一事实,并无描述应用如何更新 state。 github

store: store就是把action和reducer联系到一块儿的对象,store本质上是一个状态树,保存了全部对象的状态。任何UI组件均可以直接从store访问特定对象的状态。
Store 有如下职责:npm

再次强调一下 Redux 应用只有一个单一的 storeredux

基本原理

这个数据流的位于最中心的设计是一个AppDispatcher(应用发送器),你能够把它想成是个发送中心,不论来自组件何处的动做都须要通过它来发送。每一个store会在AppDispatcher上注册它本身,提供一个callback(回调),当有动做(action)发生时,AppDispatcher(应用发送器)会用这个回调函数通知store。设计模式

因为每一个Action(动做)只是一个单纯的对象,包含actionType(动做类型)与数据(一般称为payload),咱们会另外须要Action Creator(动做建立器),它们是一些辅助函数,除了建立动做外也会把动做传给Dispatcher(发送器),也就是调用Dispatcher(发送器)中的dispatch方法。api

Dispatcher(发送器)的用途就是把接收到的actionType与数据(payload),广播给全部注册的callbacks。它这个设计并不是是首创的,这在设计模式中相似于pub-sub(发布-订阅)系统,Dispatcher则是相似Eventbus的概念。服务器

基本使用

安装并发

npm install --save react-redux
npm install --save-dev redux-devtools

实例
主要是理解观察者模式,以及结合原理图先理解
redux的action,reducer,store基本运做。

import { createStore } from 'redux'

/**
 * This is a reducer, a pure function with (state, action) => state signature.
 * It describes how an action transforms the state into the next state.
 *
 * The shape of the state is up to you: it can be a primitive, an array, an object,
 * or even an Immutable.js data structure. The only important part is that you should
 * not mutate the state object, but return a new object if the state changes.
 *
 * In this example, we use a `switch` statement and strings, but you can use a helper that
 * follows a different convention (such as function maps) if it makes sense for your
 * project.
 */
/**
 * 来源:官网:https://github.com/reduxjs/redux
 * 
 * 第一步:定义reducer
 */
function counter(state = 0, action) {
  switch (action.type) {
    case 'INCREMENT':
      return state + 1
    case 'DECREMENT':
      return state - 1
    default:
      return state
  }
}

// Create a Redux store holding the state of your app.
// Its API is { subscribe, dispatch, getState }.

    //第二步:根据reducer规则生成store
let store = createStore(counter)

// You can use subscribe() to update the UI in response to state changes.
// Normally you'd use a view binding library (e.g. React Redux) rather than subscribe() directly.
// However it can also be handy to persist the current state in the localStorage.
    //第三步:定义数据(即state)变化以后的派发规则
store.subscribe(() => console.log(store.getState()))
store.subscribe(() => console.log(store.getState()))
store.subscribe(() => console.log(store.getState()))


// The only way to mutate the internal state is to dispatch an action.
// The actions can be serialized, logged or stored and later replayed.
   //第四步:触发数据变化
store.dispatch({ type: 'INCREMENT' })
// 1
store.dispatch({ type: 'INCREMENT' })
// 2
store.dispatch({ type: 'DECREMENT' })
// 1

常规使用

通常的文件结构,基本就是store目录下
文件

actions的操做
user.js:主要包含user模块下的action操做。

import * as types from '../constants/types'

export function loginSuccess(data) {
    return {
        type: types.LOGOIN_SUCCESS,
        payload: data
    }
}

export function logOut() {

    return {
        type: types.LOGOUT
    }
}

reducers的操做
module/user.js:定义

import * as types from '../../constants/types';

export function user(state = 0,action){
    switch(action.type) {
        case types.LOGOIN_SUCCESS:
            console.log("user......"+ action.payload);
            return state+10;
        case types.LOGOUT:
            return state - 10;
        
        default:
            return state;
    }

}

index.js
将全部reducers的集合在一块儿。

import { combineReducers } from 'redux'
import { user } from './module/user'

const rootReducer = combineReducers({
  /* your reducers */
  user
})
export default rootReducer

store的操做

import { createStore } from 'redux'
import rootReducer from './reducers'


export default function configureStore(initialState) {

    const store = createStore(rootReducer,initialState,
        window.devToolsExtension ? window.devToolsExtension() : undefined
        )
    return store
}

组件中的操做(简单)

import React from 'react';
import { bindActionCreators } from 'redux';
import { connect } from 'react-redux';
import ComA from './ComA'
import ComB from './ComB'
import * as userInfoActions from '../store/actions/user'
 class BodyIndex extends React.Component {

    componentDidMount() {
        this.props.userInfoActions.loginSuccess({
            id:'呵呵呵呵',
            username: 'bibibiibibi'
        })
    }


    render() {

        return (
            <div>
                <p>Hello world</p>
                <ComA user={this.props.user}/>
                <ComB user= {this.props.user} />
            </div>
        )
    }
}
function  mapStateToProps(state) {
    console.log("mapStateToProps...."+state);
    return {
        user: state.user.userInfo
    }
}

function mapDispatchToProps(dispatch) {
    return {
        userInfoActions: bindActionCreators(userInfoActions,dispatch)
    }
}

export default connect(
    mapStateToProps,
    mapDispatchToProps
)(BodyIndex)

组件中的操做(常规)
使用connect 这样子能够省去mapDispatchToProps,mapDispatchToProps的操做。

import React from 'react';
import { connect } from 'react-redux';
import { addComment } from '../store/actions/comment'

@connect(
    state => ({comment:state.comments.comment}),
    { addComment } 
  )
 class TestCom extends React.Component {

    componentDidMount() {
      this.props.addComment({
          comment: 100
      })  
    }


    render() {
        console.log("render...."+this.props.comment);
        return (
            <div>
                <p>TestCom.... {this.props.comment} </p>
            </div>
        )
    }
}

export default TestCom;

总结

最后,若是对 Java、大数据感兴趣请长按二维码关注一波,我会努力带给大家价值。以为对你哪怕有一丁点帮助的请帮忙点个赞或者转发哦。

相关文章
相关标签/搜索