简体   繁体   中英

redux don't show props on another page

I have a navbar for all pages. I want to make a cart in it, however, when I go to the internal product page, the props that I transmit are not displayed. 在此处输入图片说明 在此处输入图片说明

Why is this happening ? I think this is my problem React router v4 not working with Redux but how i can implement this ? What do you think ?

App.js

   import React, {Component} from 'react';
import {Container} from 'reactstrap';
import {
  BrowserRouter,
  Route,
  Switch
} from "react-router-dom";

import './App.css';
import NavbarMenu from './components/navbar'
import Main from './components/main';
import Good from './components/good';

class App extends Component {

  render() {
    return (
      <BrowserRouter>
        <div className="App">
          <NavbarMenu/>
          <Container>
            <Switch>
              <Route path="/" exact component={Main}/>
              <Route path="/good/:id" component={Good}/>
            </Switch>
          </Container>
        </div>
      </BrowserRouter>
    );
  }
}

export default App;

navbar

  import React from 'react';
import {
  Collapse,
  Navbar,
  NavbarToggler,
  NavbarBrand,
  Nav,
  UncontrolledDropdown,
  DropdownToggle,
  DropdownMenu,
  DropdownItem,
  Button
} from 'reactstrap';
import {withRouter} from 'react-router-dom';
import connect from 'react-redux/es/connect/connect';
import {getCart} from '../../redux/actions/cartAction';

class NavbarMenu extends React.Component {
  constructor(props) {
    super(props);

    this.toggle = this.toggle.bind(this);
    this.state = {
      isOpen: false
    };
  }

  toggle() {
    this.setState({
      isOpen: !this.state.isOpen
    });
  }

  render() {
console.log(this.props)
    const cartLength = this.props.cart.length;
    const cartItems = this.props.cart.map(e => {
      return <div key={e.id} style={{marginBottom: '20px'}}>
        <DropdownItem
          style={{display: 'inline-block', width: 'auto'}}
          onClick={() => {
            this.props.history.push('/good/' + e.id)
          }}>
          {e.name}
        </DropdownItem>
        <Button
          style={{display: 'inline-block', float: 'right', marginRight: '20px'}}
          color="danger"
        >X</Button>
      </div>
    });

    return (
      <Navbar
        color="light"
        light expand="md"
        style={{marginBottom: '20px'}}
      >
        <NavbarBrand
          style={{cursor: 'pointer'}}
          onClick={() => {
            this.props.history.push('/')
          }}
        >
          Shop
        </NavbarBrand>
        <NavbarToggler onClick={this.toggle}/>
        <Collapse isOpen={this.state.isOpen} navbar>
          <Nav className="ml-auto" navbar>
            <UncontrolledDropdown nav inNavbar>
              <DropdownToggle nav caret>
                Cart: {cartLength} items
              </DropdownToggle>
              <DropdownMenu right style={{width: '300px'}}>
                {cartItems}

                <DropdownItem divider/>

              </DropdownMenu>
            </UncontrolledDropdown>
          </Nav>
        </Collapse>
      </Navbar>
    );
  }
}

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

export default withRouter(connect(mapStateToProps, {getCart})(NavbarMenu));

Based on the prints you gave, you are opening the item on a diferent window, because of that, the variables on the session in the window are not passed.

One solution you could use is to save pieces of your store that you will need later in the browser localStorage.

You can do that using this by using the Redux subscribe function.

A example could be:

localStorage.js

export const loadState = () => {
  try {
    const serializedState = localStorage.getItem('state');
    if (serializedState === null) return undefined;

    return JSON.parse(serializedState);
  } catch (err) { return undefined; }
};

export const saveState = (state) => {
  try {
    const serializedState = JSON.stringify(state);
  } catch (err) {
    // errors
  }
}

And in the redux store you can put:

import { loadState, saveState } from './localStorage'; 

const persistedState = loadState();
const store = createStore(persistedState);

store.subscribe(() => saveState(store.getState()));

Source: https://egghead.io/lessons/javascript-redux-persisting-the-state-to-the-local-storage

I solved my problem by adding this code

componentDidMount() {
   this.props.getCart();
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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