1、安装
npm install --save redux
// or
yarn add redux
2、创建仓库
store是唯一的
只有store能够改变自己的内容
Reducer必须是纯函数 (纯函数:给固定的输入,就一定会有固定的输出,而且不会有任何副作用)
1、在src目录下创建一个store文件夹,然后在文件夹下创建一个index.js文件。index.js就是整个项目的store文件。
// src\store\index.js
import { createStore } from 'redux' // 引入createStore方法
const store = createStore() // 创建数据存储仓库
export default store //暴露出去
2、在store文件夹下,新建一个文件reducer.js,这个是用来管理仓库的。
// src\store\reducer.js
const defaultState = {} //默认数据
export default (state = defaultState,action)=>{ //就是一个方法函数
return state
}
state: 是整个项目中需要管理的数据信息,这里我们没有什么数据,所以用空对象来表示
3、把reducer引入到store中,再创建store时,以参数的形式传递给store
// src\store\reducer.js
import { createStore } from 'redux' // 引入createStore方法
import reducer from './reducer'
const store = createStore(reducer) // 创建数据存储仓库
export default store //暴露出去
3、组件中使用
// 1、引入store
import store from './store/index'
// 2、赋值给组件的state
constructor(props){
super(props)
this.state = store.getState()
}
// 3、UI层使用
{this.state.inputValue}