【问题标题】:React router not working as expected when pass state to history.push将状态传递给history.push时反应路由器无法按预期工作
【发布时间】:2020-01-23 15:58:31
【问题描述】:

我有一些表单,我可以在其中获取用户预订详细信息,然后在提交时我通过 history.push('/somepath') 将用户重定向到其他页面,但是当我通过 history.push({ pathname: '', state :{} }) 然后我的 url 更改但我的组件没有呈现,这是我第一次遇到这个问题,现在我的头很痛,我不知道问题出在哪里或为什么会这样。我有另一种形式,当我在那里使用 history.push({ pathname: '', state:{} }) 时效果很好。

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
        }
    });
};

【问题讨论】:

  • 只是想知道 form.js 在哪里,我的意思是在哪个父组件中?

标签: javascript reactjs react-router-v4


【解决方案1】:

我认为这应该适合你。

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

【讨论】:

  • 是的,它成功了,非常感谢你,但你能解释一下为什么会这样吗?
  • 您正在传递要推送的对象。而 push 接受两个参数,第一个作为字符串的路径,第二个作为状态的对象。
  • 但我在问题中提到的语法在我的其他 onClick 处理程序中工作正常
猜你喜欢
  • 2018-12-14
  • 1970-01-01
  • 1970-01-01
  • 2016-06-20
  • 2019-05-27
  • 2021-01-18
  • 2016-07-09
  • 2019-08-09
  • 2021-07-07
相关资源
最近更新 更多