什么是redux?简单地说,我是把它理解为一个状态管理仓库,里面可以存储状态,并且可以对这些状态进行操作。
配置redux:npm install redux
1、创建redux文件:import { createStore } from 'redux'
// 引入redux,解构 createStore
2、创建一个store对象: const store = createStore(reducer)
store对象有两个参数;
参数1是一个函数,用来接口外部传来的action
=>这个函数的名字为reducer
参数2是默认的state状态
参数3是一个中间件
//1. 引入redux,解构 createStore
import { createStore } from 'redux'
//初始化的状态
const defaultState = {
......
}
//定义reduce
const reducer = (state = defaultState,action)=>{
.......
return state
}
//2. 创建 store 对象,
//参数1是一个函数(reducer)用来接口外部传来的action
//参数2是默认的state状态
const store = createStore(reducer,defaultState)
export default store
现在讲一下store 对象的参数
reduce
reduce一个纯函数(返回值依赖于参数,并且对外界无副作用),他有两个参数。
参数1是state(是默认的state,也就是上述代码中的defaultState)
参数2是action
=>用来接收传过来的action
=>action必须是一个普通对象
+action对象内有个属性, type属性,值为string类型,表示当前要做什么
//可以把action理解为要求要进行的操作
注意:reduce只有一个,而type的意义就在于要执行的组件的方法;
可以把type理解为一个名字,这个名字跟组件的方法名相同,则调用这个方法。
中间件
store的第三个参数是一个中间件,我们该如何理解中间件?
由于用来传递信息的action只能是一个对象,当我们在写一些异步请求是一个函数的时候,浏览器就会报错。于是我们引入中间件redux-thunk,就可以正常执行了。
redux中间件,他的原理是非常简单的,他就是对store对dispatch方法做一个升级,之前这个dispatch方法只能接收一个对象,现在升级之后,就可以接收对象,也可以接收函数了。
使用方法:
1、安装redux-thunk中间件
npm install redux-thunk
2、在store中引入thunk组件
import thunk from 'redux-thunk';
const store = createStore(Reducer,applyMiddleware(thunk));
3、 action中就可以正常写函数了
现在说一下store的API:
store.getState() 获取store中的state数据
store.dispatch(action) 向store中reducer派发新的action对象
store.subscribe(()=>{}) 监听store数据的变化
工作流程:
1、store文件中创建store对象
2、组件中获取store中的state数据
=> store.getState()
3、向store中派发一个action对象
=> store.dispatch(action)
4、监听store数据变化
=> store.subscribe(()=>{})
案例:利用redux实现一个点击按钮数字加1的demo
组件
import React, { Component } from 'react'
import store from './store'
export default class Redux1 extends Component {
constructor(){
super()
this.state = store.getState()
store.subscribe(()=>{
this.setState(store.getState())
})
}
add(){
let action = {
type : 'add',
i : this.state.i + 1
}
store.dispatch(action)
}
render() {
return (
<div>
{ this.state.i }
<button onClick={this.add.bind(this)}>+</button>
</div>
)
}
}
store文件
import { createStore } from 'redux'
const defaultState = {
i:0
}
const reducer = (state = defaultState,active) => {
if(active.type === 'add'){
let tempState = JSON.parse(JSON.stringify(state))
tempState.i = active.i
return tempState
}
return state
}
const store = createStore(reducer,defaultState)
export default store