react(9)-redux

使用CRA快速创建react项目

npx create-react-app react-redux

安装配套工具

npm i @reduxjs/toolkit react-redux

启动项目

在创建项目时候会出现一个问题

You are running `create-react-app` 5.0.0, which is behind the latest release (5.0.1).

We no longer support global installation of Create React App.

Please remove any global installs with one of the following commands:

  • npm uninstall -g create-react-app

  • yarn global remove create-react-app

The latest instructions for creating a new app can be found here:

解决办法

卸载全局安装的create-react-app

javascript 复制代码
npm uninstall -g create-react-app
npx clear-npx-cache
npm i create-react-app
npx create-react-app@latest xxxxx项目名

案例:

创建store文件夹

使用store数据和方法的基本步骤

1、引入import { createSlice } from "@reduxjs/toolkit";

初始化值

//初始化state

javascript 复制代码
  initialState: {
    count: 0
  },

创建使用方法

javascript 复制代码
  // 修改状态的方法 同步方法 支持直接修改
  reducers: {
    increment: state => {
      state.count += 1;
    },
    decrement: state => {
      state.count -= 1;
    }
  }

解构导出

javascript 复制代码
// 导出actions和reducers
const { increment, decrement } = counterStore.actions;
const  reducer  = counterStore.reducer;
// 按需导出
export { increment, decrement }; 
// 默认导出
export default reducer;

整体

javascript 复制代码
import { createSlice } from "@reduxjs/toolkit";

const counterStore = createSlice({
  name: "counter",
  //初始化state
  initialState: {
    count: 0,
  },
  // 修改状态的方法 同步方法 支持直接修改
  reducers: {
    increment: (state) => {
      state.count += 1;
    },
    decrement: (state) => {
      state.count -= 1;
    },
  },
});
// 结构counterStore

// 导出actions和reducers
const { increment, decrement } = counterStore.actions;
const reducer = counterStore.reducer;
// 按需导出
export { increment, decrement };
// 默认导出
export default reducer;

2、在index文件中使用

javascript 复制代码
import { configureStore } from "@reduxjs/toolkit";
import counterReducer from "./modules/counterStore";
const store=configureStore({
  reducer: {
    counter: counterReducer
  }
});
export default store;

3、index文件中添加 Provider

javascript 复制代码
import { Provider } from 'react-redux';
import store from './store';
const root = ReactDOM.createRoot(document.getElementById('root'));
root.render(
  <React.StrictMode>
    <Provider store={store}>
    <App />
    </Provider>
  </React.StrictMode>
);

4、APP.js文件

javascript 复制代码
import { useDispatch,useSelector } from "react-redux";
import { decrement,increment } from "./store/modules/counterStore";


function App() {
 const {count}= useSelector(state=>state.counter)
 const dispatch= useDispatch()
  return (
    <div className="App">
      <button onClick={()=>dispatch(decrement())}>-</button>
      {count}
    <button onClick={()=>dispatch(increment())}>+</button>
    </div>
  );
}

export default App;

5 传参的写法

javascript 复制代码
 addToNum(state, action) {
      state.count += action.payload;
  }

不要忘记两个地方的导出

使用

javascript 复制代码
 <button onClick={()=>dispatch(addToNum(20))}>+</button>

案例2 异步获取数据

channenStore.js文件

javascript 复制代码
import { createSlice } from "@reduxjs/toolkit";
import axios from "axios";
// 创建store数据
const channelStore = createSlice({
  name: "channel",
  initialState: {
    channelList: [],
  },
  // 修改状态的方法
  reducers: {
    setChanles(state, action) {
      state.channelList = action.payload;
    },
  },
});
// 导出actions和reducers
const { setChanles } = channelStore.actions;
const reducer = channelStore.reducer;
// 异步请求部分
const fetchChannlList = () => {
  return async (dispatch) => {
    const res = await axios.get("http://geek.itheima.net/v1_0/channels");
    dispatch(setChanles(res.data.data.channels));
  };
};
export { fetchChannlList };
export default reducer;

store的index文件

javascript 复制代码
import { configureStore } from "@reduxjs/toolkit";
import counterReducer from "./modules/counterStore";
import channelReducer from "./modules/channelStore";
const store=configureStore({
  reducer: {
    counter: counterReducer,
    channel: channelReducer
  }
});
export default store;

触发

javascript 复制代码
import { useDispatch, useSelector } from "react-redux";
import { decrement, increment, addToNum } from "./store/modules/counterStore";
// 引入异步函数 channelStore的函数方法
import { fetchChannlList } from "./store/modules/channelStore";
import { useEffect } from "react";

function App() {
  const { count } = useSelector((state) => state.counter);
// 获取channelList
  const { channelList } = useSelector((state) => state.channel);


  const dispatch = useDispatch();
  // 触发异步函数
  useEffect(() => {
    dispatch(fetchChannlList())
  },[dispatch])


  return (
    <div className="App">
      <button onClick={() => dispatch(decrement())}>-</button>
      {count}
      <button onClick={() => dispatch(increment())}>+</button>
      <button onClick={() => dispatch(addToNum(20))}>+</button>
  
  {/* 列表展示 */}
      <ul>
        {channelList.map((item) => (
          <li key={item.id}>{item.name}</li>
        ))}
      </ul>
  
  
    </div>
  );
}

export default App;
相关推荐
陈随易4 分钟前
Postman 被曝自动往 Claude Code 和 Codex 装插件
前端·后端·程序员
Dream-Y.ocean2 小时前
鸿蒙PC平台宅匠 3D 室内设计适配实战:基于 Electron 壳方案的 Three.js 双渲染引擎与参数化户型编辑器开发
javascript·3d·harmonyos
Csvn3 小时前
性能监控
前端
Highcharts.js3 小时前
Highcharts Gantt使用符号的自定义数据标签开发甘特图示例
javascript·甘特图·highcharts·图表开发·实战代码·响应式图表
Csvn4 小时前
构建工具
前端
FRing034 小时前
vue2干货总结3(computed计算属性、watch监听器)
开发语言·前端·vue.js·vue2
JavaPub-rodert5 小时前
从零搭建通用管理后台:ShiyuAdmin 的 Go、React 与 RBAC 实践
开发语言·react.js·golang
kyriewen6 小时前
Skills 榜前 10 我全装了:只有 3 个能直接用
前端·javascript·程序员
IT_陈寒7 小时前
当Java的hashCode遇上Lombok,我的缓存被全清了
前端·人工智能·后端
工控丫丫7 小时前
帆软看板中经常使用的公式函数及经常搭的组合
前端·javascript·数据库