Reactjs 浏览器路由器-如何访问历史记录?更改组件或操作中的位置?

Reactjs 浏览器路由器-如何访问历史记录?更改组件或操作中的位置?,reactjs,react-router-v4,browser-history,Reactjs,React Router V4,Browser History,我在我的React/Redux应用程序中使用BrowserRouter,因此我不会创建history对象,也不会将其传递给BrowserRouter,因为它处理自己的历史。目前,我模拟了登录功能,这是login组件中的函数(它调用loginthunk inauthActions): handleSubmit=(e)=>{ e、 预防默认值(); this.props.authActions.login({ 电子邮件:this.state.email, 密码:this.state.passwor

我在我的
React/Redux
应用程序中使用
BrowserRouter
,因此我不会创建
history
对象,也不会将其传递给
BrowserRouter
,因为它处理自己的历史。目前,我模拟了登录功能,这是
login
组件中的函数(它调用
login
thunk in
authActions
):

handleSubmit=(e)=>{
e、 预防默认值();
this.props.authActions.login({
电子邮件:this.state.email,
密码:this.state.password
});

};我的建议是:更改
componentDidMount
lifecyclehook中的位置

你有一些
道具要比较,做一些动作等等

当您创建用于管理位置更改的HOC时,效果会更好

更新

首先,NO更改
render
func中的位置,这将生成错误

根据你的应用程序结构,有很多解决方案。。。 另一个解决方案是使用“componentWillReceiveProps”

componentWillReceiveProps(nextProps, nextState){
  if(nextProps.isLoggedIn===true&&this.props.isLoggedIn===false){
    nextProps.history.push('path_for_logged_in')
  }
}
对于props中的访问历史记录,您需要使用
withRouter
HOC包装组件

import { withRouter } from 'react-router'


withRouter(YourComponent)

从react router dom与router一起使用。ex:为了访问操作中的历史记录,您需要在分派操作时从组件传递历史记录,或者您可以创建历史记录对象,请参阅更多详细信息。因此,react-router-v4不支持从上下文访问路由器,您可以看看这个答案:无法在
componentDidMount
中更改位置,因为在登录时正确的凭据后,即在发送
成功登录
操作后,应该立即更改位置。所以它应该在action(thunk)或组件的登录函数中,该函数在单击时调用。所以,生命周期挂钩不是解决方案。