A jump react interfacial interface jump B interface, returns A interface, the interface A remains unchanged in the state method redux

Told you react in interface A jump B, returns to A, A state of the interface remains the same, the article used the traditional method of localStorage in the previous article, now using the state to achieve the second method redux this feature

Now I am new redux, it is not very likely some advanced methods will be used, here using a very simple way. In fact, these two methods principles are similar with the original data saved by or reload the data to achieve

I am here with a shopping cart of goods for the simple example, we can be increased according to their own scenes, the principles are the same

First define a way to save your data in the action.js

// actions.js 

// related merchandise 
Export add_to_cart = const 'add_to_cart' ; 
Export DELETE_TO_CART const = 'DELETE_TO_CART' ; 
Export UPDATE_TO_CART const = 'UPDATE_TO_CART' ;
 / * value of correlation * / 
Export const the ADD = 'the ADD' ; 
Export const the SUB = 'SUB' ;
 / * flag associated * / 
Export const fLAG = 'fLAG' ; 
Export function addToCart (product, the Quantity, UnitCost) {// product list I want to save the
     return { 
        of the type: the add_to_cart,  
        payload: {product, quantity, unitCost}
    } 
} 
Export  function flag (flag) {// flag to determine based on this flag is not loaded with the data or re-requesting data
     return { 
        type: the FLAG, 
        payload: flag {} 
    } 
}

redux folder there are three files, one commodity, one flag, one is to merge these two together

// src/reducers/cart-reducer.js
import {ADD_To_CART, DELETE_TO_CART,UPDATE_TO_CART} from "../action";
//初始化state
const initialState = {
    cart: [
        {
            product: 'bread 700g',
            quantity: 2,
            unitCost: 90
        },
        {
            product: 'milk 500ml',
            quantity: 1,
            unitCost: 57
        }
    ]
}
export default function (state = initialState, action){
    switch (action.type) {
        case ADD_To_CART: {
            return {
                ...state,
                cart:[...state.cart,action.payload]
            }
        }
        case DELETE_TO_CART:{
             return {
                ...state,
                 cart:state.cart.filter((item,key)=>{
                     if(item.product!=action.payload.product){
                         return item;
                     }
                 })
             }
        }
        case UPDATE_TO_CART:{
            return {
                ...state,
                cart:state.cart.map((item,key)=>{
                    if(item.product == action.payload.product){
                        return action.payload
                    }
                    else{
                        return item
                    }
                })
            }
        }
        default : return state
    }
}
// src/reducers/flag-reducer.js
import {FLAG} from '../action'
export default function (state=false,action){
   switch (action.type) {
       case FLAG :
           return action.payload.flag
       default :
           return state
   }
}
import {combineReducers} from 'redux';
import productReducer from './product-reducer';
import cartReducer from './cart-reducer'
import flagSlogn from './flag-reducer'
const allReducer = {
    product:productReducer,
    shoppingCart : cartReducer,
    flagSolgn:flagSlogn
}
const rootReducer = combineReducers(allReducer);
export default  rootReducer

Then create store.js

import {createStore} from 'redux';
import rootReducer from './reducer'
let store = createStore(rootReducer);
export default store

Use your js interface

React Import, {from} the Component 'REACT' ; 
Import from Store '../store/store' 
Import {the addToCart, deleteToCart, updateToCart,} In Flag from "../store/action" ; 
Import} from {Link 'react- DOM-Router ' ; 
class Home the extends React.Component { 
    constructor (The props) { 
        Super (The props); 
        the this .STATE = { 
            Cart: [], 
        } 
    } 
    componentDidMount () { IF (. store.getState () flagSolgn) {/ / judgment is not a jump button, click on the sub-interface time from loading the original data returned by
             the this .setState ({ 
                Cart:. store.getState () shoppingCart.cart  
            })
        }
        else{   //没有点击,就按照初始化的来
            this.setState({
                cart:[]
            })
            store.dispatch(addToCart('Coffee 500mg', 1, 250));
            store.dispatch(addToCart('Flour lkg', 2, 440));this.setState({
                cart: store.getState().shoppingCart.cart
            })
        }

    }
    addProduct(){
        store.dispatch(addToCart('Green Tea',5,25));
       this.setState({
            cart:store.getState().shoppingCart.cart,
         
        })
    }
    render() {
        const {cart} = this.state;
        return (
            <div>
                <ul>
                {
                  cart.map((item,key)=>{
                      return (
                          <li key={key}><ul><li>{item.product}</li><li>{item.quantity}</li><li>{item.unitCost}</li></ul></li>
                      )
                  })
                }
                </ul>
                <Link to={{pathname:"/HomePage"}}>跳转子界面</Link>
                <div>
                    <button onClick={this.addProduct.bind(this)}>增加</button>
                </div>
            </div>
        )
    }

}

export default Home;

Content sub-interface can easily write, after all, you just need to return to the parent from the child screen interface, the interface remains unchanged parent effect, you just need that when entering sub-interface, change the flag just fine

import React, {Component} from 'react';
import store from '../store/store'
import {add, flag, sub} from '../store/action'
class HomePage extends React.Component {
    constructor(props) {
        super(props);
        this.state = {
            count:0
        }
    }
    componentDidMount() {
        store.dispatch(flag(true));  //父界面进入子界面的标志位
    }

    addCount(){
        store.dispatch(add(2));
        this.setState({
            count:store.getState().product
        })
    }
    subCount(){
        store.dispatch(sub(3));
        this.setState({
            count:store.getState().product
        })
    }
    render() {
        const {count} = this.state;
        return (
            <div>
              子界面得到store
                {store.getState().shoppingCart.cart[0].product}
                <div>
                <button onClick={this.addCount.bind(this)}>增加</button>
                </div>
                <div>
                <button onClick={this.subCount.bind(this)}>减少</button>
                </div>
                <p>数值: {count}</p>
            </div>
        )
    }
}
export default HomePage;

Then you can put the other interface other than the flag becomes false, like

Note: here recommend a beginner to learn redux example, speak very clearly  https://segmentfault.com/a/1190000011474522?utm_source=tag-newest

Guess you like

Origin www.cnblogs.com/yesu/p/10978592.html