此处以一个加减的方式,用来举例子
- 首先在src中新建一个store文件夹, store中创建一个index.js
引入createStore, 在redux中引入
// 新建一个仓库
import { createStore } from 'redux'
import reducer from './reducer'
// store是唯一的,多个store是不被允许的
// 只有store可以改变自己的内容, reducer是不能改变的
// reducer是一个纯函数
const store = createStore(reducer)
// 导出仓库
export default store
- 在store中新建reducer.js,然后在index.js中引入
// 创建reducer
const defaultState = {
inputValue: '请输入value',
data: [],
count: 0
}
// eslint-disable-next-line import/no-anonymous-default-export
export default (state = defaultState, action) => {
// 书写处理的业务逻辑
console.log(state, action)
const newState = JSON.parse(JSON.stringify(state))
switch(action.type) {
case CHANGEVALUE:
newState.inputValue = action.value
return newState
case ADDITEM:
newState.data.push(newState.inputValue)
newState.inputValue = ''
return newState
case DETEITEM:
newState.data.splice(action.index, 1)
return newState
case TWO:
newState.count += 2
return newState
case SUBTWO:
newState.count -=2
return newState
case dataList:
newState.data = action.data
return newState
default:
return state
}
}
在src中store文件夹中新建一个actionType.js文件处理其中的类型的说明
const CHANGEVALUE = 'changeInputValue'
const ADDITEM = 'addItem'
const DETEITEM = 'deteItem'
const TWO = 'two'
const SUBTWO = 'subtwo'
const dataList = 'dataList'
export {
CHANGEVALUE,
ADDITEM,
DETEITEM,
TWO,
SUBTWO,
dataList
}
在src中store文件夹中新建一个actionCreatore.js.js文件处理其中的函数的说明
const changeValueAction = (type, value) => {
return {
type,
value
}
}
const addItemAction = (type) => {
const action = {
type
}
return action
}
const deleteItemAction = (type, index) => {
return {
type,
index
}
}
const addTwoAction = (type) => {
return {
type
}
}
const subtwoAction = (type) => {
return {type}
}
const getListAction = (type, data) => {
return {
type,
data
}
}
export {
changeValueAction,
addItemAction,
deleteItemAction,
addTwoAction,
subtwoAction,
getListAction
}
- 在react组件中的使用
import React from 'react'
import store from '../../store/index'
// 引用类型
import {
TWO,
SUBTWO
} from '../../store/actionType'
// 引用函数
import {
addTwoAction,
subtwoAction
} from '../../store/actionCreatore'
export default class Reduxdemo extends React.Component {
constructor(props) {
super(props)
// 得到redux中state中的数据
this.state = store.getState()
// 创建changeStore
this.changeState = this.changeState.bind(this)
}
componentDidMount () {
// 在subscibe重新绘制dom
store.subscribe(this.changeState)
}
changeState () {
this.setState(store.getState())
}
addTwo () {
store.dispatch(addTwoAction(TWO))
}
subTwo () {
store.dispatch(subtwoAction(SUBTWO))
}
render () {
return (
<div>
<div>{this.state.count}</div>
<button onClick={this.addTwo.bind(this)}>+2</button>
<button onClick={this.subTwo.bind(this)}>-2</button>
</div>
)
}
}
本篇结束