# ShoppingCart+Redux

# 布局要求

![商品列表](/Users/zhaotianwei/Desktop/全栈-10/07 react/机试/A卷/素材/A卷.png)

![购物车](/Users/zhaotianwei/Desktop/全栈-10/07 react/机试/B卷/素材/B 卷 - 02.png)

# 需求

# 商品列表

  • 实现axios请求API数据
  • 获取数据渲染列表
  • 顶部size多选筛选
  • order排序
  • 商品添加购物车
  • 添加购物车数据持久化

# 购物车

  • 购物车列表渲染
  • 删除购物车商品
  • 单件商品数量增加和减少
  • 总数量计算
  • 总价计算
  • 选中删除
  • 全选删除

# 项目创建和准备

# create-react-app 创建项目

create-react-app 姓名_班级_日期
1

# 安装依赖库

# react-router-dom 路由模块
npm install react-router-dom
1
# redux react-redux
npm install redux react-reddux
1
# antd
npm install antd
1
# axios
npm install axios
1

# 创建工程结构

  • public

  • src

    component

    page

    redux

    ​ actions.js

    ​ actionType.js

    ​ index.js

    ​ reducer.js

    Router.js

# 具体实现逻辑

# axios请求数据

在商品列表页面组件请求数据

//引入 axios 
import axios from "axios"

//在组件的componenDidMount周期函数中请求网络数据
componentDidMount(){
  //axios 请求数据
  /*
  参数描述:
  url:请求资源路径
  response:请求成功的响应(响应的数据放在response.data中)
  error:请求失败的错误信息
  
  axios.get(URL).then((response)=>{
  
	}).catch((error)=>{
	
	})

  */
  axios.get("http://www.hostName.com/api/list").then((response)=>{
    //获取请求成功数据
  }).catch((error)=>{

  })
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25

# 集成 Redux

# 创建 store

在redux模块中创建redux的入口文件 index.js,在index中创建store

//从 redux 引入 createStore 和 combineReducers 函数
import {createStore, combineReducers} from "redux"

/*
combineReducers函数参数描述:
对象:包含所有reducer的对象
key-value形式:key值是对应reducer的名称 ,值是reducer函数,
*/
const rootReducer = combineReducers({
  shoppingList:shoppingListReducer
})

/*
初始化的state对象
*/
const initialState = {};

/*
	createStore函数参数描述:
	参数1 rootReducer:调用combineReducers函数合并所有reducer返回到的对象
	参数2 initialState:初始化的state对象
*/
const store = createStore(rootReducer,initialState);
//导出store
export default store;
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
# 使用store,集成redux

改造应用程序的入口文件 index.js

//引入 Provier 组件
import {Provider} from "react-redux"
// 引入创建好的store
import store from "./redux/index"

// 使用Providder组件包裹程序的根组件,并且指定store属性
ReactDOM.render(
  <Provider store={store}>
    <App />
  </Provider>, document.getElementById('root'));
1
2
3
4
5
6
7
8
9
10

# 将axios获取到的数据添加到shoppingListReducer中的state中,使用redux管理状态

Last Updated: 8/9/2022, 4:24:39 PM