一、Redux的基本使用-概念理解

83 阅读1分钟

核心概念

- Store
- Store中的数据来自 reducer 函数 返回一个state
- store.dispatch({type: payload})
- 这里的派发操作也会给 reducer函数
- function reducer(state, action) { return new State}

基本使用

import { createStore } from 'redux'

// 1. 初始化数据
const initialState = {
  name: 'luffy',
  age: 18
}

// 3. 创建reducer函数
function reducer(state = initialState, action) {
    // 返回一个新的state的纯函数
    switch(action.type) {
        case 'changeAge':
          return { ...state, age: state.age + action.num }

        default:
          return state
    }
}

// 2. 创建一个store 接收一个reducer的函数
const store = createStore(reducer)

// 发起阶段action 修改state数据
store.dispatch({
    type: 'changeAge',
    num: 10
})

// 获取store的数据   -->  自动订阅触发
// console.log(store.getState())

// 自动监听触发 订阅模式 store的数据变化
store.subscribe(() => {
>   // store数据发生改变的时候就会重新执行这个回调
  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)

// 使用的时候 action 应该被函数创建
const nameAction = {
    type: 'change_name',
    name: 'luffy'
}

function actionCreator(name) {
    return {
        type: 'change_name',
        name
    }
}

store.dispatch(nameAction)