目录
一.redux的认识
redux 和react没有什么直接的关系,在React, Angular, Ember, jQuery, or vanilla JavaScript中都可以使用Redux。
Redux 帮助你管理“全局”状态 - 那些应用程序的许多部分都需要的状态。
二.什么时候使用redux
- 在应用的大量地方,都存在大量的状态
- 应用状态会随着时间的推移而频繁更新
- 更新该状态的逻辑可能很复杂
- 中型和大型代码量的应用,很多人协同开发
三.安装redux
npm install redux
四.redux的使用
1.创建store
import { legacy_createStore as createStore } from 'redux';
import Reducer from './reducer';
let store = createStore(Reducer);
export default store;
2.创建reducer
import { ADD_CAR, ADD_BUY_NUM, SUBTRACT_BUY_NUM } from './action';
const state1 = {
carArr: [],
};
const goodCar = (state = state1, action) => {
const { type, data } = action;
switch (type) {
case ADD_CAR:
return getAddCarData(data, state.goodCar);
case SUBTRACT_BUY_NUM:
return changeBuyNum(state.goodCar, data.id, '-');
case ADD_BUY_NUM:
return changeBuyNum(state.goodCar, data.id, '+');
default:
return state.carArr;
}
};
// 点击 购物车按钮
const getAddCarData = (obj, arr) => {
if (obj) {
if (arr.length == 0) {
return [...arr, { ...obj, buyNum: 1 }];
} else {
const idArrs = arr.map((item) => item.id);
if (idArrs.includes(obj.id)) {
let index = arr.findIndex((item) => item.id == obj.id);
arr[index].buyNum = arr[index].buyNum + 1;
return arr;
} else {
return [...arr, { ...obj, buyNum: 1 }];
}
}
} else {
return arr;
}
};
// 点击 + | —号
const changeBuyNum = (arr, id, flag) => {
let index = arr.findIndex((item) => item.id == id);
arr[index].buyNum = flag == '+' ? arr[index].buyNum + 1 : arr[index].buyNum - 1;
return arr;
};
const Reducer = (state, action) => {
return {
goodCar: goodCar(state, action),
};
};
export default Reducer;
3.创建action
export const ADD_CAR = 'ADD_CAR';
export const ADD_BUY_NUM = 'ADD_BUY_NUM';
export const SUBTRACT_BUY_NUM = 'SUBTRACT_BUY_NUM';
4.在页面中引入store
(1)在商品列表页引入store
import { PageContainer, ProTable } from '@ant-design/pro-components';
import { Button, Drawer, Input, message } from 'antd';
import React, { useRef, useState } from 'react';
import { history } from 'umi';
import store from '../../store/store.js';//引入store
const GoodList = () => {
const tableData = [
{
id: 1,
name: '包子',
num: 5,
price: 2,
},
{
id: 2,
name: '面条',
num: 500,
price: 10,
},
{
id: 3,
name: '鸡蛋灌饼',
num: 300,
price: 5,
},
{
id: 4,
name: '烤肠',
num: 700,
price: 3,
},
];
const columns = [
{
title: 'id',
dataIndex: 'id',
},
{
title: '商品名称',
dataIndex: 'name',
},
{
title: '库存量',
dataIndex: 'num',
},
{
title: '单价',
dataIndex: 'price',
},
{
title: '操作',
valueType: 'option',
key: 'option',
render: (text, record, _, action) => [
<a
key="addCar"
onClick={() => {
clickAddCarBtn(record);
// action?.startEditable?.(record.id);
}}
>
加入购物车
</a>,
],
},
];
// 点击 添加购物车按钮
const clickAddCarBtn = (obj) => {
console.log('添加购物车按钮:', obj);
store.dispatch({ type: 'ADD_CAR', data: { ...obj } });
history.push('/carList');
};
return (
<PageContainer>
<ProTable rowKey="id" search={false} columns={columns} dataSource={tableData} />
</PageContainer>
);
};
export default GoodList;
(2)在购物车页面引入store
import { PageContainer, ProTable } from '@ant-design/pro-components';
import { Button, Drawer, Input, message, Card } from 'antd';
import React, { useRef, useState, useEffect } from 'react';
import store from '../../store/store.js';//引入store
import style from './index.less';
const CardList = () => {
const [carNewArr, setCarNewArr] = useState([]);
let actionRef = useRef();
const [num, setNum] = useState(0);
useEffect(() => {
console.log('store:', store.getState());
// 商品购物车数组
getBuyNumData();
}, [num]);
console.log('carNewArr:', carNewArr);
const columns = [
{
title: 'id',
dataIndex: 'id',
},
{
title: '商品名称',
dataIndex: 'name',
},
{
title: '库存量',
dataIndex: 'num',
},
{
title: '单价',
dataIndex: 'price',
},
{
title: '购买数量',
valueType: 'option',
key: 'option',
render: (text, record, _, action) => [
<div key="buyNum" className={style.card}>
{record.buyNum > 0 ? (
<div
className={style.circle}
onClick={() => {
changeBuyNum(record, '-');
}}
>
-
</div>
) : null}
<div className={style.buyNum}>{record.buyNum}</div>
{record.buyNum < record.num ? (
<div
className={style.circle}
onClick={() => {
changeBuyNum(record, '+');
}}
>
+
</div>
) : null}
</div>,
],
},
];
const getBuyNumData = () => {
const carObj = store.getState();
setCarNewArr(carObj?.goodCar);
};
//修改购物车的数量
const changeBuyNum = (obj, flag) => {
store.dispatch({ type: flag == '+' ? 'ADD_BUY_NUM' : 'SUBTRACT_BUY_NUM', data: { ...obj } });
setNum(num + 1);
};
return (
<PageContainer>
<Card>
<ProTable rowKey="id" search={false} columns={columns} dataSource={carNewArr} />
</Card>
</PageContainer>
);
};
export default CardList;
五.运行效果图
图1
图2
图3
图4