Redux 与 Redux Toolkit示例

Redux示例:

插件依赖:

npm install redux

npm install react-redux

------------------------------------------------------------

yarn add redux

yarn add react-redux

一个redux应该包括一个reducer,每个reducer就是redux中数据的更新逻辑,不过这个reducer可以是很多个reducer组成。

store/counterReducer.js 

/**
 * 这是一个 reducer 函数:接受当前 state 值和描述“发生了什么”的 action 对象,它返回一个新的 state 值。
 * reducer 函数签名是 : (state, action) => newState
 *
 * Redux state 应该只包含普通的 JS 对象、数组和原语。
 * 根状态值通常是一个对象。 重要的是,不应该改变 state 对象,而是在 state 发生变化时返回一个新对象。
 *
 * 你可以在 reducer 中使用任何条件逻辑。 在这个例子中,我们使用了 switch 语句,但这不是必需的。
 * 
 */


export default function counterReducer(state={value:0,name:'',age:18}, action) {
  switch (action.type) {
    case 'counter/incremented':
      return { value: state.value + 1 }
    case 'counter/decremented':
      return { value: state.value - 1 }
    default:
      return state
  }
}

 store/movieReducer.js 

export default function movieReducer(state={value:0,name:'',age:18}, action) {
  switch (action.type) {
    case 'counter/incremented':
      return { value: state.value + 1 }
    case 'counter/decremented':
      return { value: state.value - 1 }
    default:
      return state
  }
}

stroe/combineReducers .js 该文件用于将众多的reducer结合,生成一个reducer,用于创建redux

import { combineReducers } from 'redux'

import counterReducer from './counterReducer '
import movieReducer from './movieReducer '

export default combineReducers({ counterReducer, movieReducer })

store/index.js 创建redux

import { createStore } from 'redux'
import combineReducers from './combineReducers '
export default createStore(combineReducers )

// 使用中间件
// import { createStore, applyMiddleware } from 'redux'
// import thunk from 'redux-thunk'
// import rootReducer from './reducers'
// export default createStore(rootReducer, applyMiddleware(thunk))

 使用插件包裹根组件

import {Provider} from "react-redux"
import { BrowserRouter as Router } from "react-router-dom";
import store from "@/store/index.js"    

     
        
    

view/storeTest.js 测试文件

// import { useState } from "react";
import { useDispatch, useSelector } from "react-redux";

export default () => {
//   const [count, useCount] = useState(0);
  const state = useSelector((state) => state.counterReducer);
  const dispatch = useDispatch()
  const handleClick = () => {
    console.log(state);
    dispatch({type:"counter/incremented"})
  };
  return (
    

store Test

count : --- {state.value}


); };

Redux Toolkit示例:

插件依赖:

npm install react-redux @reduxjs/toolkit

------------------------------------------------------------------

yarn add react-redux @reduxjs/toolkit

store/index.js

import { configureStore } from "@reduxjs/toolkit";

import counterSlice from "./counterSlice"; //slice,每个slice相当于一个小块的reducer

import movieSlice from "./movieSlice";

export default configureStore({ //暴漏创建的store
  reducer: { //每个store只允许有一个reducer,不过这个reducer可以是许多个小块拼接而成
    counter: counterSlice,
    movie: movieSlice,
  },
});

store/counterSlice.js

import { createSlice } from "@reduxjs/toolkit"; 

export const counterSlice = createSlice({  //创建 slice
  name: "counterSlice",
  initialState: { //状态初始值
    count: 0,
  },
  reducers: { //可执行的reducer
    increment(state, { payload }) {
      state.count = state.count + payload.step; // 内置了immutable
    },
    decrement(state, action) {
      console.log(action);
      state.count -= 1;
    },
  },
});
export const { increment, decrement } = counterSlice.actions;  //暴露方法,方便在需要使用的页面引入
export default counterSlice.reducer  //暴露出reducer,创建store时需要

//movieSlice同上

 store/movieSlice.js

import { createSlice } from "@reduxjs/toolkit";

export const counterSlice = createSlice({
  name: "counterSlice",
  initialState: {
    countM: 0,
  },
  reducers: {
    incrementM(state, { payload }) {
      state.countM = state.countM + payload.step;
    },
    decrementM(state, action) {
      console.log("movie");
      state.countM -= 1;
    },
  },
});
export const { incrementM, decrementM } = counterSlice.actions;
export default counterSlice.reducer

views/storeTest.js

// import store from "../store";
import { useSelector, useDispatch } from "react-redux";
import { increment, decrement } from "../store/counterSlice";
import { incrementM, decrementM } from "../store/movieSlice";

export default () => {
  const dispatch = useDispatch();  //通过hooks可以直接获取dispatch方法
  const { countM } = useSelector((state) => state.movie);  //获取不同slice的值
  const { count } = useSelector((state) => state.counter);
  const handleClick = (type) => {
    type === "+"
      ? dispatch(increment({ step: 1 }))  // 提交action,进行状态更新
      : dispatch(decrement({ step: 1 }));
  };
  const handleClickM = (type) => {
    type === "+"
      ? dispatch(incrementM({ step: 1 }))
      : dispatch(decrementM({ step: 1 }));
  };
  return (
    

store Test

count : --- {count}


countM : --- {countM}


); };

 最后注意在使用Provider包裹根组件:

import {Provider} from "react-redux"
import { BrowserRouter as Router } from "react-router-dom";
import store from "@/store/index.js"    

     
        
    

redux中文官网:https://cn.redux.js.org/introduction/getting-started

你可能感兴趣的:(react,前端)