二、Redux核心语法与文件拆分

80 阅读1分钟

Store仓库创建

// store.js
import { createStore } from 'redux'
import reducer from './reducer.js'

const store = createStore(reducer)

export default store

Reducer.js

import { CHANGE_NAME, CHANGE_AGE } from './constants'

const initialState = {
    name: '',
    age: 16
}
function reducer(state = initialState, action) {
    switch (action.type) {
        // 这里的数据类型可以定义为常量
        case CHANGE_NAME:
          return { ...state, name: action.name }
    
        case CHANGE_AGE:
          return { ...state, age: state.age + action.num}

        default:
          return state
    }
}

export default reducer

constants

export const CHANGE_NAME = 'change_name'
export const CHANGE_AGE = 'change_age'

使用阶段 action 创建

const changeNameAction = (name) => ({
    type: CHANGE_NAME,
    name
})

const changeAgeAction = (age) => ({
    type: CHANGE_AGE,
    age
})

const addNumAction = (num) => ({
        
})

使用

store.dispatch(changeNameAction('luffy')) // 重新执行reducer函数

app.jsx中使用

每一次使用都需要引入store 做数据监听派发, 每个组件都会有大量重复代码 这个时候需要封装一个高阶组件,实际项目中使用 react-redux

import React, { PureComponent } from "react"

import store from "./store"

export class App extends PureComponent {
  constructor() {
    super();
    this.state = {
      counter: store.getState().counter, // 获取初始值
    };
  }
  
  // 数据发生改变 订阅模式监听数据变化 派发
  componentDidMount() {
    store.subscribe(() => {
      const state = store.getState();
      this.setState({
        counter: state.counter,
      });
    });
  }

  btnClick(num) {
      // 传入一个action 从action.js文件导入
      store.dispatch(addNumAction(num))
  }
  
  render() {
    let { counter } = this.state
    return (
      <div className="app">
        <h2>App页面计数器: {counter}</h2>
        <button onClick={() => this.btnClick(num)}></button>
      </div>
    );
  }
}

export default App;