react+redux项目搭建及示例
阅读原文时间:2023年07月08日阅读:2

目录结构

1.项目搭建

1.1 使用create-react-app react_redux创建项目

1.2 安装使用redux需要的依赖 npm install redux react-redux redux-devtools

2.添加一些文件夹

2.1创建储存常量的文件夹添加cart.js

export const ADD_CART = "ADD_CART"
export const UPDATE_CART = 'UPDATE_CART';
export const DELETE_FROM_CART = 'DELETE_FROM_CART';

2.2创建action文件夹添加cart.js

import { ADD_CART, UPDATE_CART, DELETE_FROM_CART } from '../contants/cart'
export const addCart = function (product, quantity, unitCost) {
    return {
        type: ADD_CART,
        payload: { product, quantity, unitCost }
    }
}
export const updateCart = function (product, quantity, unitCost) {
    return {
        type: UPDATE_CART,
        payload: { product, quantity, unitCost }
    }
}
export const deleteFromCart = function (product) {
    return {
        type: DELETE_FROM_CART,
        payload: { product }
    }
}

2.3创建reducers文件夹

2.3.1 cart.js

import { ADD_CART, UPDATE_CART, DELETE_FROM_CART } from '../contants/cart'
const initialState = {
  shops: [
    {
      product: '面包',
      quantity: 2,
      unitCost: 90
    },
    {
      product: '牛奶',
      quantity: 1,
      unitCost: 47
    }
  ]
}
const cartReducer = function (state = initialState, action) {
  switch (action.type) {
    case ADD_CART: {
      return {
        ...state,
        shops: [...state.shops, action.payload]
      }
    }

    case UPDATE_CART: {
      return {
        ...state,
        shops: state.shops.map(item => {
          item = item.product === action.payload.product ? action.payload : item
          return item
        })
      }
    }

    case DELETE_FROM_CART: {
      return {
        ...state,
        shops: state.shops.filter(item => item.product !== action.payload.product)
      }
    }

    default:
      return state
  }
}

export default cartReducer

2.3.2productsReducer.js

const productsReducer = function (state = [], action) {
    return state
}
export default productsReducer

2.3.3index.js

import { combineReducers } from 'redux'
import cartReducer from './cart'
import productsReducer from './productsReducer'

const allReducers = {
    cart: cartReducer,
    products: productsReducer
}

const rootReducer = combineReducers(allReducers)//合并reducer
export default rootReducer

2.4创建store

import { createStore } from 'redux'
import rootReducers from '../reducers'

import { composeWithDevTools } from 'redux-devtools-extension';
// composeWithDevTools 在控制台可以查看数据
let store = createStore(rootReducers, composeWithDevTools())

console.log("initial state: ", store.getState());

export default store;

3.修改src下index.js

import React from 'react';
import ReactDOM from 'react-dom';
import './index.css';
import App from './App';
import * as serviceWorker from './serviceWorker';
import store from './store/index'
import { Provider } from 'react-redux'

ReactDOM.render(<Provider store={store}>
    <App />
</Provider>, document.getElementById('root'));

// If you want your app to work offline and load faster, you can change
// unregister() to register() below. Note this comes with some pitfalls.
// Learn more about service workers: https://bit.ly/CRA-PWA
serviceWorker.unregister();

4.修改App.js

import React, { Component } from 'react';
import { connect } from 'react-redux'
import './App.css';
import * as cartActions from './actions/cart'

class App extends Component {
  constructor(props) {
    super(props)
  }
  render() {
    let { shops } = this.props.cart;
    return (
      <div className="App">
        <ul>
          {shops.map((s, index) => {
            return <li key={index}>{s.product}===>{s.quantity}===>{s.unitCost}</li>
          })}
        </ul>
        <hr />
        <button onClick={() => this.props.addCart()} > 增加商品</button>
        <button onClick={() => this.props.updateCart()} > 修改商品</button>
        <button onClick={() => this.props.deleteCart()} > 删除商品</button>
      </div>
    )
  }
}

function getState(state) {
  return {
    cart: state.cart
  }
}

function getDispatch(dispatch) {
  return {
    addCart: () => dispatch(cartActions.addCart("鱼香肉丝", 1, 20)),
    updateCart: () => dispatch(cartActions.updateCart("鱼香肉丝", 2, 50)),
    deleteCart: () => dispatch(cartActions.deleteFromCart("鱼香肉丝"))
  }
}

export default connect(getState, getDispatch)(App);

初次使用redux做的小demo,记录一下