# 简易redux项目

包含首页,商品列表,和详情页。还有注册页面。



# 步骤分解


1、项目入口main.js



2、AppRouter注意加Provider,加载的是主入口 Index,需要store,所以后面创建store



3、Index入口里面才是各个实际组件



4、创建store



5、需要reduces,所以创建 homeReducer.js,确定Home页面的默认初始state


import { deepCopy } from "../deepCopy";
import { HOME_INIT } from "../actionCreators/actionTypes";

export let homeReducer = (state = {
   bannerList: [],
   goodsList: []
}, action) => {
   let newState = deepCopy(state);
   switch (action.type) {
       // 4、reducer接收到之后进行store数据的更新
       case HOME_INIT:
           newState.bannerList = action.bannerList;
           newState.goodsList = action.goodsList;
           return newState;
       default:
           return state;
   }
} 


6、reducers的集合到Reducer/index.js文件



7、来看具体组件,只看个Home组件,采用自动创建容器组件的方式。
Home加载完成时,请求ajax数据。


import { connect } from "react-redux";

import { Banner } from "../components/Banner";
import { List } from "../components/List";
import { Nav } from "../components/Nav";
import { homeInitAction } from "../actionCreators/actions";

/* UI部分 */
class UI extends React.Component {
   constructor() {
       super();
   }

   // 1、组件加载完成获取ajax数据
   componentDidMount() {
       this.props.homeInit();
   }

   render() {
       let { bannerList, goodsList } = this.props;
       return (
           <div>
               <nav>
               <banner bannerlist="{bannerList}">
               <list goodslist="{goodsList}">
           </list></banner></nav></div>
       );
   }
}

/* 容器部分 */
// 5、视图和store绑定
let mapStateToProps = ({ homeReducer }) => homeReducer;

let mapDispatchToProps = dispatch => {
   return {
       // 2、Ajax数据有actions.js函数获取
       homeInit() {
           dispatch(homeInitAction);
       }
   }
}

export let Home = connect(mapStateToProps, mapDispatchToProps)(UI); 


8、获取ajax需要action,于是创建actions.js ,期间会用到actionTypes.js


import axios from 'axios';
import async from 'async';
import { HOME_INIT, GOODS_INIT, DETAIL_INIT, SUBMIT_ITEM } from './actionTypes';

//home
export let getHomeData = (bannerList, goodsList) => {
   return {
       type: HOME_INIT,
       bannerList,
       goodsList
   }
}

export let homeInitAction = dispatch => {
   async.parallel({
       bannerList(cb) {
           axios.get('/zhuiszhu/goods/getHot').then(({ data }) => {
               cb(null, data.list);
           })
       },
       goodsList(cb) {
           axios.get('/zhuiszhu/goods/getList').then(({ data }) => {
               cb(null, data.list);
           })
       }
   }, (err, data) => {
       if (!err) {
           // 3、获取到数据后派发给reducer
           dispatch(getHomeData(data.bannerList, data.goodsList));
       }
   })
} 


将获取到的数据发送给了reducer,由于homeReducer已经创建了,只需要switch case匹配更新store数据即可。


9、由于已经在Home.js绑定视图和store同步。


// 5、视图和store绑定
let mapStateToProps = ({ homeReducer }) => homeReducer; 


于是Home组件显示成功!其他Goods,Detail,Register组件同理。


TIPS:有一点需要注意:就是容器组件如何获取UI组件中input输入的值: