简体   繁体   English

在使用 react-router 和 redux 时,如何维护我的商店的 state?

[英]How can I maintain my store's state while using react-router and redux?

I am building an app prototype that essentially simulates ecommerce.我正在构建一个本质上模拟电子商务的应用程序原型。 I have components that each have different items that can be added to a cart(below I just show an example of how one would basically work).我有组件,每个组件都有可以添加到购物车中的不同项目(下面我只是展示一个基本如何工作的示例)。 These components are accessed via different routes using the react-router.使用 react-router 通过不同的路径访问这些组件。 There is a header component that displays the number of items currently in the cart.有一个 header 组件显示当前购物车中的商品数量。 The header gets the number of items in the cart from the state in the redux store. header 从 redux 商店中的 state 获取购物车中的商品数量。 However, if I navigate to a new route, the store goes back to the default state.但是,如果我导航到新路线,商店将返回默认的 state。 I need the the store to keep its state when a new route is navigated to.当导航到新路线时,我需要商店保留其 state。 For example, if I go to the ShoppingPage, add an item to the cart, and then go back to the Home page, I need the cart to still have an item in it.例如,如果我 go 到 ShoppingPage,将商品添加到购物车,然后 go 回到主页,我需要购物车中仍有商品。

actions.js动作.js

export const actionTypes = Object.freeze({
    UPDATE_CART: Symbol('UPDATE_CART'),
});

export const updateCart = (payload) => {
    return {
        type: actionTypes.UPDATE_CART,
        payload,
    };
};

export default actionTypes;

reducer.js减速器.js

import actions from './actions';

export const INITIAL_STATE = {
    cart: [],
};

export default (state = INITIAL_STATE, action) => {
    switch (action.type) {
        case actions.UPDATE_CART: {
            return {
                ...state,
                cart: action.payload,
            };
        }
        default: {
            return state;
        }
    };
};

index.js index.js

import React from 'react';
import ReactDOM from 'react-dom';
import App from './App';
import * as serviceWorker from './serviceWorker';
import { BrowserRouter } from 'react-router-dom';
import { Provider } from 'react-redux';
import { createStore } from 'redux';
import reducer, { INITIAL_STATE } from './reducer';

const store = createStore(reducer, INITIAL_STATE);
console.log(store.getState());
ReactDOM.render(
<Provider store ={store}>
    <BrowserRouter>
        <App />
    </BrowserRouter>
</Provider>
, document.getElementById('root'));

serviceWorker.unregister();

ShoppingPage.js ShoppingPage.js

import React, { Component } from 'react';
import { connect } from 'react-redux';
import { updateCart } from './actions';

class ShoppingPage extends Component {
    addToCart = () => {
        const cart = [...this.props.cart];
        cart.push('new item');
        this.props.modifyCart(cart);

    render() {
        return(
            <div>
                <button onClick={addToCart}>
                    Add To Cart
                </button>
            </div>
        )
    }
}

const mapDispatchToProps = dispatch => ({
    modifyCart: payload => dispatch(updateCart(payload)),
});

const mapStateToProps = state => ({
    cart: state.cart,
});

export default connect(
    mapStateToProps,
    mapDispatchToProps,
)(ShoppingPage);

Home.js主页.js

import React, { Component } from 'react';
import { ListGroup, ListGroupItem } from 'reactstrap';

class Home extends Component {
    render() {
        return(
            <div>
                <ListGroup>
                    <ListGroupItem><a href='/ShoppingPage'>ShoppingPage</a></ListGroupItem>
            </div>
        )
    }
}

export default Home;

Header.js Header.js

import React, { Component } from 'react';
import { Navbar, NavbarBrand } from 'reactstrap';
import { connect } from 'react-redux';

class Header extends Component {
    render() {
        return(
            <Navbar sticky='top' className='nav'>
                <NavbarBrand href='/'>Online Shopping</NavbarBrand>
                    <span>{'Items in Cart: '}{this.props.cart.length}</span>
            </Navbar>
        )
    }
}

const mapStateToProps = state => ({
    cart: state.cart,
});

export default connect(
    mapStateToProps
)(Header);

Routes.js路由.js

import React from 'react';
import { Switch, Route } from 'react-router-dom';
import Home from './Home';
import ShoppingPage from './ShoppingPage';

const Routes = () => (
    <Switch>
        <Route exact path='/' component={Home} />
        <Route exact path='/ShoppingPage' component={ShoppingPage} />
    </Switch>
);

export default Routes;

App.js应用程序.js

import React from 'react';
import Routes from './Routes';
import Header from './Header';

function App() {
  return (
    <div>
        <Header />
        <Routes />
    </div>
  );
}

export default App;

What's likely happening is that during navigation the web app "reloads" again (which is wiping the redux state).可能发生的情况是,在导航期间 web 应用程序再次“重新加载”(正在擦除 redux 状态)。 In order to navigate with react router you want to look at <Link> .为了使用反应路由器导航,您需要查看<Link>

For example,例如,

Home.js主页.js

<a href='/ShoppingPage'>ShoppingPage</a>

should be changed to:应改为:

<Link to="/ShoppingPage">ShoppingPage</Link>

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM