二、修改数据 store.dispatch(action)
src/store/index.js
import { createStore } from 'redux' // 引入方法
import reducer from './reducer'
const store = createStore(reducer) // 创建数据存储仓库
export default store
src/store/reducer.js
const defaultState = {
num : 1
}
function fn (state = defaultState,action){
state = JSON.parse(JSON.stringify(state)) //深度拷贝state
switch (action.type) {
case "NUM":
state.num = action.num
return state;
default:
return state;
}
}
const state=fn
export default state
组件使用:
src/views/a.js
import React from 'react'
import store from '../store/index'
class A extends React.Component {
constructor(props){
super(props)
this.state=store.getState();
this.storeChange = this.storeChange.bind(this)
store.subscribe(this.storeChange)
}
changeInputValue(e){
if(e.target.value){
const action ={
type:'NUM',
num:JSON.parse(e.target.value)
}
store.dispatch(action)
}else{
const action ={
type:'NUM',
num:e.target.value
}
store.dispatch(action)
}
}
storeChange(){
this.setState(store.getState())
}
addClick(){
var count=this.state.num +1
const action ={
type:'NUM',
num:count
}
store.dispatch(action)
}
reduceClick(){
var count=this.state.num -1
const action ={
type:'NUM',
num:count
}
store.dispatch(action)
}
render() {
return (
<div >
<p>
<button onClick={this.reduceClick.bind(this)}>减1</button>
<input value={this.state.num} type="number" onChange={this.changeInputValue}/>
<button onClick={this.addClick.bind(this)}>加1</button>
</p>
</div >
)
}
}
export default A
补充:
1、bind(this) 解决:如果传递一个函数名给一个变量,然后通过在变量后加括号()来调用这个方法,此时方法内部的this的指向就会丢失。
2、主要用subscribe监听store,当store中数据发生变化就会更新数据 。
3、JSON.parse(JSON.stringify(state)) ,关于深度拷贝可去参考这位兄台的博客