7. redux

1、所有的状态统一放在state中,由store来管理state

2、用户触发一个action行为,由dispatch分发action行为

3、通过store把原有的state的状态值和dispatch分发的action行为一起传给reducer

4、Reducer的作用是返回一个新的state去更新原有的store中对应的state

5、Store接收到新的state然后重新渲染Component

6、每一次store中的state发生变化,通过subscribe这个方法进行监听的,只要是store中的状态发生变化了,那么就会触发这个方法从而实现组件的更新

 

 

action

Action本质就是一个对象,它有一个type属性,type属性是用来判断用户触发的是哪一个行为(是汉译英还是英译汉,就是使用的type来进行判断的),再实际使用的时候并不是直接用的action,而是使用action创建的一个函数,这个函数返回的是一个action

Function add(){    --------------------->add这个action行为对象

Return {type:’add’}

}

 

Reducer

Reducer就是一个纯函数,回接收两个参数,第一个参数是需要管理的状态state,第二个参数是action

Reducer回根据传入的action中的type值对state进行不同的操作,从而返回一个新的state,不是再原有的state上进行修改的,如果遇到未知的actiontype值,不会对原有的state进行任何修改,返回的是原有的state

Function reducer(state,action){

Switch(action.type){}

}

Store:

包含整个redux应用的所有状态,需要使用createStore方法生成一个新的store

Store提供的三个方法:

Store.getState()用来获取state值得

Store.dispatch()  用来改变状态得

Store.subscribe() 用来监听state变化得,每当state变化就会调用这个方法

简单小实例//

import React from 'react'
import ReactDom from 'react-dom' ;
import {createStore} from "redux"
class HelloB extends React.Component{
    constructor(props){
        super(props);
        this.state={
            msga:"你好,世界"
        }
        store.subscribe(()=>{   
            this.setState({
                msga:store.getState().msg
            })
        })
    }
    
    changeLanguage=()=>{
        store.dispatch(actions.sendEnglish())
    }

    render(){
        return(  
                <div>
                    <h1>{this.state.msga}</h1>
                    <button onClick={this.changeLanguage}>翻译</button>
                </div>
        )
    }

}

const actions={
    sendChinese:()=>({type:"chinese"}),
    sendEnglish:()=>({type:"english"})
}

const reducer=(state={},actions)=>{
    switch(actions.type){
        case "chinese":
            return{
                state,
                msg:"你好,世界"
            }
        case 'english':
            return{
                state,
                msg:"hellw word"
            }
        default:
            return state
    }
}

const store=createStore(reducer)  //通过接收reducer返回得新的state值生成新的state


ReactDom.render(
     
    <HelloB/>,
   document.getElementById("root")
)
原文地址:https://www.cnblogs.com/taozhibin/p/13065590.html