核心概念
- Store
- Store中的数据来自 reducer 函数 返回一个state
- store.dispatch({type: payload})
- 这里的派发操作也会给 reducer函数
- function reducer(state, action) { return new State}
基本使用
import { createStore } from 'redux'
const initialState = {
name: 'luffy',
age: 18
}
function reducer(state = initialState, action) {
switch(action.type) {
case 'changeAge':
return { ...state, age: state.age + action.num }
default:
return state
}
}
const store = createStore(reducer)
store.dispatch({
type: 'changeAge',
num: 10
})
store.subscribe(() => {
>
console.log('数据发生改变', store.getState())
})
action 优化
import { createStore } from 'redux'
function reducer(state = initialState, action) {
switch(action.type) {
case 'changeAge':
return { ...state, age: state.age + action.num }
default:
return state
}
}
export const store = createStore(reducer)
const nameAction = {
type: 'change_name',
name: 'luffy'
}
function actionCreator(name) {
return {
type: 'change_name',
name
}
}
store.dispatch(nameAction)