redux是javascript状态容器,我觉得它分为三部分:reducer,store,action。
三者之间的关系:
每个应用中只有一个store,每个store中可以有很多个reducer,在reducer中有一个action属性。例如: action{type:"increatment",data}。
每个状态都是存在于store中的,如果想改变状态就要触发action。描述action是如何改变state的,需要编写reducer.js。
也就是说,有store中的index.js,引入reducer.js,在reducer.js中编写action用来改变state。
最后在app函数中引入store中改变状态的函数,并在app中写好页面,写好事件。
运行。
思想实现:
创建store文件夹下的index.js文件,引入redux,并创建reducer
import { createStore} from 'redux'
//整个应用只有一个store,reducer有很多个去处理事务
const store = createStore(reducer);
export default store
我们需要在reducer.js下编写实现操作的代码。例如:实现点击+增加数字,点击 - 减少数字。
默认初始state是0;在action下有type作为表示,如果为increment则,state+1,decrement则state-1;写好将reducer导出。
//配合store执行 ; action{type:"increatment",data}
const defaultState = 0
const reducer = (state=defaultState, action) => {
switch (action.type) {
case "increment":
return state+1
case "decrement":
return state-1
default:
return state
}
}
export default reducer
在reducer中写完需要在store中引入,我觉得store就像一个上级一样,reducer像他的下属,用来打杂,而store只是在窃取“reducer”的劳动成果。
import { createStore} from 'redux'
import reducer from "./reducer"
//整个应用只有一个store,reducer有很多个去处理事务
const store = createStore(reducer);
export default store
都写完了之后,我们来到视图层,view层编写APP组件,首先写好页面,有一个显示的数字,有两个按钮,分别是加和减。
<p>
Clicked:{this.state.count} times
<button onClick={this.increament}>+</button>
<button onClick={this.decreament}>-</button>
</p>
初始获取到state中的count属性----注意-----count属性存在于store中的getState中,即初始值表示为:
this.state={//获取初始值
count:store.getState()
}
渲染完视图层页面后,我们开始写事件,点击事件 加减法:此处用到dispatch属性,调用store中的type表示,当触发增加事件时,就type为标志“increment”,触发减少事件时,就type为标志“decrement”。(store层是用来改变state的)。
increament=()=>{
store.dispatch({type:"increment"})
}
decreament=()=>{
store.dispatch({type:"decrement"})
}
那如果时普通的更改state属性呢,如下:没有store的事
increment=()=>{
this.setState(prestate=>({count:prestate.count+1}))
}
decrement=()=>{
this.setState(prestate=>({count:prestate.count-1}))
}
事件写完后,当我们测试时会发现,点击后,可以更改数字,但是并不同步渲染页面,于是利用到一个同步函数,用来即时渲染页面视图层。,传递回调事件。
syncState=()=>{
this.setState({count:store.getState()})
}
当监听到有状态变化时,就会执行这个函数,同步视图层页面。写好函数之后记得要在初始调用
store.subscribe(this.syncState)
即,监听到有状态发生改变时,就渲染页面。
至此,完成一个简单的有思路的,编写redux的思路流程。