action 创建函数
action 用来表示有事情发生
action创建函数就是生成action的方法,redux的action创建函数只是简单的返回一个action
function addTodo(text) {
return {
type: ADD_TODO,
text
}
}
redux中只要把action创建函数的结果传递给dispatch()就可以发起一次dispatch
reducer
reducer 当action发生时,用来改变state数据
reducer是纯函数,不能修改传入的参数,不能执行有副作用的操作,如api操作和路由跳转,不用调用非纯函数如Date.now()
reducer 根据action的情况和原来的state,输出新的state
function todoApp(state = initialState, action) {
switch (action.type) {
case SET_VISIBILITY_FILTER:
return Object.assign({}, state, {
visibilityFilter: action.filter
})
default:
return state
}
}
state的初始值是undefined redux首次执行时应该为其赋值initialState
在遇到未知的action时返回原state
Object.assign(),不能把state放在第一个参数上,这样会改变state的值,用一个空对象,用state的数据填充进去,再用对应action的操作修改 返回一个新的对象
store
getState()
获取当前state
他与store最后一个reducer的返回值相同
dispatch(action)
分发action,这是出发state改变的唯一方式
会使用当前 getState()
的结果和传入的 action
以同步方式的调用 store 的 reduce 函数。返回值会被作为下一个 state。从现在开始,这就成为了 getState()
的返回值,同时变化监听器(change listener)会被触发
createStore(reducer, [initialState])
创建一个store来存放应用中所有的state
应用中应该有且仅有一个store
参数
- reducer 接受两个参数 state 和 action
- 初始state
返回值
(Store):保存了所有的state,唯一改变的方法是dispatch(action),也可以设置一个subscribe(listener)
import { createStore } from 'redux'
function todos(state = [], action) {
switch (action.type) {
case 'ADD_TODO':
return state.concat([ action.text ])
default:
return state
}
}
let store = createStore(todos, [ 'Use Redux' ])
store.dispatch({
type: 'ADD_TODO',
text: 'Read the docs'
})
console.log(store.getState())
// [ 'Use Redux', 'Read the docs' ]
subscribe(listener)
添加一个变化监听器,每当 dispatch(action)的时候就会执行,state中的一部分可能已经变化,可以在回调函数中调用getState()来拿到当前state
function select(state) {
return state.some.deep.property
}
let currentValue
function handleChange() {
let previousValue = currentValue
currentValue = select(store.getState())
if (previousValue !== currentValue) {
console.log('Some deep nested property changed from', previousValue, 'to', currentValue)
}
}
let unsubscribe = store.subscribe(handleChange)
handleChange()
replaceReducer(nextReducer)
替换原有的reducer