【发布时间】:2020-07-21 17:22:32
【问题描述】:
我在 react-redux 项目中使用 react-router-dom 5.1.2。对于我的路由,我有 2 个文件。第一个是 App.js,其中包含 redux 商店和 BrowserRouter 的提供者:
import React from 'react';
import {Provider} from "react-redux";
import {configureStore} from "../store";
import {BrowserRouter as Router} from "react-router-dom";
import Navbar from "./Navbar";
import Main from "./Main";
import {setAuthorizationToken, setCurrentUser} from "../store/actions/auth";
import jwtDecode from "jwt-decode";
const store = configureStore();
if (localStorage.jwtToken) {
setAuthorizationToken(localStorage.jwtToken);
// prevent someone from manually tampering with the key of jwtToken in localStorage
try {
store.dispatch(setCurrentUser(jwtDecode(localStorage.jwtToken)));
} catch (e) {
store.dispatch(setCurrentUser({}));
}
}
const App = () => (
<Provider store={store}>
<Router>
<div className="onboarding">
<Navbar />
<Main />
</div>
</Router>
</Provider>
);
export default App;
在下一层,我有 Main.js,它包含到我所有组件的路由
import React from "react";
import {Switch, Route, withRouter, Redirect} from "react-router-dom";
import {connect} from "react-redux";
import Homepage from "../components/Homepage";
import AuthForm from "../components/AuthForm";
import {authUser} from "../store/actions/auth";
import {removeError} from "../store/actions/errors"
import withAuth from "../hocs/withAuth";
import GameForm from "./GameForm";
import GamePage from "../components/GamePage";
import FighterForm from "./FighterForm";
const Main = props => {
const {authUser, errors, removeError, currentUser} = props;
return (
<div className="container">
<Switch>
<Route path="/" exact render={props => <Homepage currentUser={currentUser} {...props} /> } />
<Route
path="/signin" exact
render={props => {
return(
<AuthForm
removeError={removeError}
errors={errors}
onAuth={authUser}
buttonText="Log in"
heading="Welcome Back."
{...props}
/>
)
}} />
<Route
path="/signup" exact
render={props => {
return(
<AuthForm
removeError={removeError}
errors={errors}
onAuth={authUser}
signUp
buttonText="Sign me up"
heading="Join Weekly Matchup today."
{...props}
/>
)
}}
/>
<Route
path="/games/new" exact
component={withAuth(GameForm)}
/>
<Route
path="/games/:game_id/fighters/new" exact
component={withAuth(FighterForm)}
/>
<Route
path="/games/:game_id"
render={props => {
return(
<GamePage
currentUser={currentUser}
{...props}
/>
)
}}
/>
<Redirect to="/" />
</Switch>
</div>
)
}
function mapStateToProps(state){
return {
currentUser: state.currentUser,
errors: state.errors
};
}
export default withRouter(connect(mapStateToProps, {authUser, removeError})(Main));
我遇到的问题是,当我使用 path = "/games/:game_id/fighters/new" 的路线时,它没有显示 FighterForm.js,而是重定向回 "/"。
我尝试在 Switch 中上下移动路线,但没有产生任何变化。我还将路径更改为仅有效的“/fighter/new”(路线显示了表格);但是,我需要在参数中包含 :game_id 才能在 post call 中使用它来进行商店操作。
如何在 react-router 中创建具有这种深度的路由?
【问题讨论】:
标签: redirect routing react-redux routes react-router