在goBack()响应路由器v4之前检查历史记录之前的位置

ted*_*ted 16 javascript ecmascript-6 reactjs react-router

我的目标是启用"返回"按钮,但前提是用户返回的路径/路径属于某个类别.

更准确地说,我有两种路线:/<someContent>/graph/<graphId>.当用户在图表之间导航时,他们应该能够返回到上一个图形但不能返回到/...路径.这就是为什么我不能简单地运行history.goBack(),我需要先检查位置.

const history = createHashHistory();
const router = (
        <ConnectedRouter history={history}>
            <Switch>
                <Route exact path='/' component={Home}></Route>
                <Route exact path='/extension' component={Home}></Route>
                <Route exact path='/settings' component={Home}></Route>
                <Route exact path='/about' component={Home}></Route>
                <Route exact path='/search' component={Home}></Route>
                <Route exact path='/contact' component={Home}></Route>
                <Route path='/graph/:entityId' component={Graph}></Route>
            </Switch>
        </ConnectedRouter>
);
Run Code Online (Sandbox Code Playgroud)

我想在Graph组件中实现这样的东西:

if (this.props.history.previousLocation().indexOf('graph') > -1){
    this.props.history.goBack();
} else {
    this.disableReturnButton();
}
Run Code Online (Sandbox Code Playgroud)

这个问题也适用于goForward()我想要禁用"前进"按钮,如果不适用.用户也随身携带this.props.history.push(newLocation)

显然我想避免在用户移动时使用登录localStorage或者redux 等侧面技巧store,感觉不那么自然,我知道该怎么做.

Shu*_*tri 14

在通过Link组件导航时,甚至history.push可以将当前位置传递给另一个Route组件

喜欢

<Link to={{pathname: '/graph/1', state: { from: this.props.location.pathname }}} />
Run Code Online (Sandbox Code Playgroud)

要么

history.push({
  pathname: '/graph/1',
  state: { 
      from: this.props.location.pathname
  }
})
Run Code Online (Sandbox Code Playgroud)

然后你可以只在您的组件一样得到这个位置this.props.location.state && this.props.location.state.from,然后再决定是否wan't到goBack与否

  • **更新**:是的,您可以使用 [useLocation](https://reacttraining.com/blog/react-router-v5-1/#uselocation) (3认同)

lis*_*tdm 6

使用context您可以存储以前的位置pathname

const RouterContext = React.createContext();

const RouterProvider = ({children}) => {
  const location = useLocation()
  const [route, setRoute] = useState({ //--> it can be replaced with useRef or localStorage
    to: location.pathname,
    from: location.pathname
  });

  useEffect(()=> {
    setRoute((prev)=> ({to: location.pathname, from: prev.to}) )
  }, [location]);
  
  return <RouterContext.Provider value={route}>
    {children}
  </RouterContext.Provider>
}
Run Code Online (Sandbox Code Playgroud)

然后,在某些组件中RouterProvider

const route = useContext(RouterContext);

 //...
 <Link to={route.from}>
     Go Back
 </Link>
Run Code Online (Sandbox Code Playgroud)