redux
原理图
创建一个全局的store
// 引入createStore,用于创建store对象
import {createStore,applyMiddleware} from "redux"
// 下载这个redux-thunk,用于支持异步action
import thunk from "redux-thunk"
// 引为Count服务的reducer
import countReducer from "./count_reducer"
// 在applyMiddleware里面包上中间件thunk
export default createStore(countReducer,applyMiddleware(thunk))
在最外层的index.js文件 监听store数据的改变,重新渲染页面
import React from "react"
import ReactDOM from "react-dom"
import App from "./App"
import store from "./store"
ReactDOM.render(<App/>,document.getElementById('root'))
store.subscribe(()=>{
ReactDOM.render(<App/>,document.getElementById('root'))
})
创建Reducer 上面用到的count_reducer
// 创建一个为count组件服务的reducer, 本质上就是一个函数,有两个参数,之前的状态preState,和action动作对象
import {INCREMENT,REDUCE} from "./statant"
const initState = 0
export default function countReducer(preState=initState,action){
const {type,data} = action
switch(type){
case INCREMENT:
return preState + data
case REDUCE:
return preState - data
default:
return preState
}
}
store.getState() 获取reducer中的初始化值
静态名称 stant.js 文件
export const INCREMENT = "increment"
export const REDUCE = 'reduce'
创建count_action
import {INCREMENT,REDUCE} from "./statant"
export const createIncrementAction = data =>({type:INCREMENT,data})
export const createReduceAction = data =>({type:REDUCE,data})
// 异步action 就是action的值是函数,异步action中一般会调用同步action , dispatch是函数默认自带的参数
export const createAsyncIncrementAction = (data,time) =>{
return (dispatch)=>{
setTimeout(()=>{
dispatch(createIncrementAction(data))
},time)
}
}
使用
引用store
import store from "./store.js"
引用action,用于创建action对象
import {createIncrementAction,createReduceAction} from './count_action.js'
在需要用到它的地方使用
store.dispatch(createIncrementAction(value))