react+redux項目搭建及示例


React + Redux示例,實現商品增刪改

目錄結構

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,記錄一下


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM