简体   繁体   中英

React router not working as expected when pass state to history.push

I have some form where i get user reservation details and then on submit i redirect user to other page by history.push('/somepath') but when i pass props by history.push({ pathname: '', state:{} }) then my url changes but my component is not rendered, this is the first time im facing this problem and now my head hurts, I dont know where the problem is or why this is happening. I have another form which works fine when i use history.push({ pathname: '', state:{} }) there.

App.js

import React from 'react';
import { connect } from 'react-redux';
import { BrowserRouter, Switch, Route, Redirect } from 'react-router-dom';
import Navbar from './components/Navbar/Navbar';
import Home from './pages/Home/Home';
import Login from './pages/Login/Login';
import Signup from './pages/Signup/Signup';
import Vehicles from './pages/Vehicles/Vehicles';
import About from './pages/About/About';
import VehiclesListView from './pages/Vehicles/VehiclesListView';
import Checkout from './pages/Checkout/Checkout';

function App({ user }) {
    const [ isAuth, setAuth ] = React.useState(false);

    return (
        <BrowserRouter basename="/">
            <Navbar isAuth={isAuth} setAuth={(v) => setAuth(v)} />
            <Switch>
                <Route exact path="/" component={Home} />
                <Route path="/vehicles" component={Vehicles} />
                <Route exact path="/reserve/checkout" component={Checkout} />
                <Route exact path="/reserve" component={VehiclesListView} />
                <Route path="/about" component={About} />

                {!user && (
                    <Switch>
                        <Route path="/login" render={() => <Login setAuth={(v) => setAuth(v)} />} />
                        <Route path="/signup" component={Signup} />
                    </Switch>
                )}
                <Redirect to="/" />
            </Switch>
        </BrowserRouter>
    );
}

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

export default connect(mapStateToProps)(App);

Form.js

const submit = (e) => {
    e.preventDefault();
    history.push({
        pathname: `/reserve?type=${type}&zipcode=${pickup.zip}`,
        state: {
            type,
            pickup,
            dropOff,
            pickupTime,
            dropTime
        }
    });
};

I think this should work for you.

history.push(`/reserve?type=${type}&zipcode=${pickup.zip}`, 
      state: {
            type,
            pickup,
            dropOff,
            pickupTime,
            dropTime
     }
);

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