gpt4 book ai didi

javascript - 将状态传递给history.push时,React路由器无法按预期工作

转载 作者:行者123 更新时间:2023-12-02 22:00:53 25 4
gpt4 key购买 nike

我有某种形式,可以获取用户预订详细信息,然后在提交时通过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);

表单.js

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

最佳答案

我认为这应该适合你。

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

或者像这样,

history.push({
pathname: '/reserve',
search: '?type=${type}&zipcode=${pickup.zip}',
state: { detail: response.data }
})

关于javascript - 将状态传递给history.push时,React路由器无法按预期工作,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59882549/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com