一、什么是Store
① 产生store
const store = createStore(reducer)
② store的方法:
getState():得到状态
dispatch(action):dispatchaction给reducer
subscribe(listener):当store有任何变化的时候都会调用他的回调函数
二、什么是action
action就是一个普普通通的对象,描述了更新state的操作,就像setState一样。但是它只是一个对象,只有描述,没有真正的去更新Store(Store中的state)
{
type:ADD_TODO,
text:'asdaasdasdasf'
}
三、什么是reducer
reducer是一个纯函数,接受两个参数,第一个是初始状态,第二个是action
例如:
function reducer = (initialState, action) {
if(action.type === ADD_TODO) {
return Object.assign({}, state, {
todos: [
...state.todos,
{
text: action.text,
completed: false
}
]
})
}
return state
}
所有的reducer会接收到所有的action,一个action通过store的dispatch()方法dispatch出去,所有reducer方法都会接收到action,如果action.type符合则执行。
四、redux是如何工作的
首先,从dispatch开始,dispatch一个action出去,然后reducer会接收到action,最后根据action更新store中的state,产生一个新的state
五、常用的工具函数
① combineReducers
将系统中所有的reducer结合到一起来
import { combineReducers } from 'redux'
import reducer1 from './xxx'
import reducer2 from './xxx'
const store = createStore( combineReducers({
reducer1,
reducer2
}))
② bindActionCreators
将action的创建和dispatch集合到一个一个函数里面,实现操作步骤的简化
function plusOne() {
return {type: 'xxx'}
}
//plusOne被包装了
plusOne = bindActionCreators(plusOne, Store.dispatch)
//直接调用plusOne,实现了dispatch
plusOne()
六、具体实例
import React from 'react';
import {
createStore,
combineReducers,
bindActionCreators
} from 'redux';
import { act } from 'react-dom/test-utils';
function run() {
//Store initial state
const initialState = { count: 0 }
//reducer
const counter = (state = initialState, action) => {
switch (action.type) {
case "PLUS_ONE":
return { count: state.count + 1 }
case "MINUS_ONE":
return { count: state.count - 1 }
case "CUSTOM_COUNT":
return { count: state.count + action.payload.count }
default:
break
}
return state
}
const todos = (state = {}) => state
//Create store
const store = createStore(
combineReducers({
todos,
counter
})
)
//Action creator
function plusOne() {
//action
return { type: 'PLUS_ONE' }
}
function minusOne() {
return { type: "MINUS_ONE" }
}
function customCount() {
return { type: "CUSTOM_COUNT", payload: { count } }
}
plusOne = bindActionCreators(plusOne, store.dispatch)
store.subscribe(() => console.log(store.getState()))
// store.dispatch(plusOnew())
plusOne();
store.dispatch(minusOne())
store.dispatch(customCount(5))
}
export default () => (
<div>
<button onClick={run}>Run</button>
<p>请打开控制台查看结果</p>
</div>
)
参考文档:https://redux.js.org/introduction/getting-started
参考视频:https://time.geekbang.org/course/detail/100009301-9449?utm_source=pinpaizhuanqu&utm_medium=geektime&utm_campaign=guanwang&utm_term=guanwang&utm_content=0511