Skip to content

一、redux网页引用

1、redux的引用

html
<script src="https://unpkg.com/redux@4.2.0/dist/redux.js"></script>

2、创建redux的store仓库对象

Redux是一个状态容器,所以使用Redux必须先创建容器对象,它的所有操作都是通过容器对象来进行的,创建容器的方式有多种

createStore用来创建一个Redux中的容器对象,它需要三个参数:reducerpreloadedStateenhancer

  • reducer是一个函数,是state操作的整合函数,每次修改state时都会触发该函数,它的返回值会成为新的state
  • preloadedState就是state的初始值,可以在这里指定也可以在reducer中指定
  • enhancer增强函数用来对state的功能进行扩展
js
const store = Redux.createStore(countReducer);

3、store仓库的数据使用

  • 1.读取state
js
store.getState()
  • 2.修改state
js
store.dispatch({type:"ADD"})

dipatch用来触发state的操作,可以将其理解为是想reducer发送任务的工具。它需要一个对象作为参数,这个对象将会成为reducer的第二个参数action,需要将操作信息设置到对象中传递给reducer。action中最重要的属性是type,type用来识别对state的不同的操作,上例中’ADD’表示增加操作,’SUB’表示减少的操作。

  • 3.监听state

subscribe方法,这个方法用来订阅state变化的信息。该方法需要一个回调函数作为参数,当store中存储的state发生变化时,回调函数会自动调用

js
store.subscribe(()=>{
    // store中state发生变化时触发
});

4、示例

js
const reducer=(state={count:1},action)=>{
	switch(action.type){
		case 'ADD':
			return {...state,count:count.state+=1};
		case 'SUB'
			return {...state,count:count.state-=1};
		case 'ADD_N':
			return {...state,count:count.state+count.action.payload}
		default:
			return state
	}
}
const store=Redux.createStore(reducer)

store.subscribe(()=>{
	countSpan.innerText=store.getState().count
})

subBtn.addEventListener('click',()=>{
	store.dispatch({type:'SUB'})
})