我正在为我的应用程序使用 React v4.2,它似乎与路线的正确路径不匹配:
<Provider store={store}>
<BrowserRouter>
<div>
<Switch>
<Route path="/login" render={(props) => {
if (isAuthenticated()) {
return <Redirect to='/' />;
} else {
return <LoginForm {...props}/>
}
}
} />
<EnsureLoggedInContainer>
<Route exact path="/group" render={(props) => {
debugger;
return <GroupList {...props}/>
}
}/>
<Route exact path="/group/new" render={(props) => {
debugger;
return <GroupList {...props} modal={rr}/>;
}
} />
</EnsureLoggedInContainer>
</Switch>
</div>
</BrowserRouter>
</Provider>
我在应用程序中有一些链接,单击这些链接会将客户端重定向到新 URL:
_onSubmit(values) {
const { history } = this.props;
this.props.createGroup(values, ({status}) => history.push('/group'));
}
我检查 props.history.location.pathname
的值和props.match.path
而且它们不匹配。为什么会发生这种情况?为什么没有匹配到正确的路由?
更新1
EnsureLoggedInContainer
的代码:
class EnsureLoggedInContainer extends Component {
componentDidMount() {
if (!isAuthenticated()) {
dispatch(setRedirectUrl(currentURL))
this.props.history.replace("/login")
}
}
render() {
if (isAuthenticated()) {
return(
<div>
<AppNavBar />
<ComponentsNavBar />
{this.props.children}
</div>
);
} else {
return <noscript />;
}
}
}
export default EnsureLoggedInContainer;
更新2
我将路由器配置代码更改为以下内容:
ReactDOM.render(
<Provider store={store}>
<BrowserRouter>
<div>
<Switch>
<Route exact path="/login" render={(props) => {
if (isAuthenticated()) {
return <Redirect to='/' />;
} else {
return <LoginForm {...props}/>
}
}
} />
<Route exact path="/register" render={(props) => {
if (isAuthenticated()) {
return <Redirect to='/' />;
} else {
return <RegisterForm {...props}/>
}
}
} />
<EnsureLoggedInContainer>
<Route exact path="/group" component={GroupList} modal={newGroupModal}/>
<Route exact path="/group/new" component={GroupList}/>
<Route component={Home} />
</EnsureLoggedInContainer>
</Switch>
</div>
</BrowserRouter>
</Provider>
, document.querySelector('.container'));
并更改了 EnsureLoggedInContainer
的最后一行至:
export default withRouter(EnsureLoggedInContainer);
但是,我仍然得到 Home
始终被渲染,并且随机 URL 与不相关的路由匹配(例如 /group/new
)
最佳答案
根据文档:
A
match
object contains information about how a matched the URL. match objects contain the following properties:params - (object) Key/value pairs parsed from the URL corresponding to the dynamic segments of the path isExact - (boolean) true if the entire URL was matched (no trailing characters) path - (string) The path pattern used to match. Useful for building nested <Route>s url - (string) The matched portion of the URL. Useful for building nested <Link>s
同时
Locations represent where the app is now, where you want it to go, or even where it was.
因此,如果您位于 /group/new
上,location.pathname
将为您提供 /group/new
而 match .path
将为您提供为您在其中记录的组件定义的路由路径(如果匹配)
关于javascript - React Router 路径错误匹配,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48515602/