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

时间:2017-11-21 09:29:33

标签: javascript reactjs ecmascript-6 react-router

我的目标是启用" Go Back"按钮,但仅当用户返回的路径/路径属于某个类别时。

更准确地说,我有两种路线:/<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>
);

我想在Graph组件中实现类似的内容:

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

这个问题也适用于goForward(),因为我想禁用&#34;转发&#34;按钮,如果不适用。用户也可以使用this.props.history.push(newLocation)

移动

显然,当用户四处移动时,我希望避免使用登录localStorage或redux store这样的伎俩,感觉不太自然,我知道该怎么做。

3 个答案:

答案 0 :(得分:8)

在导航Link组件或history.push时,您可以将当前位置传递到另一个Route组件

<Link to={{pathname: '/graph/1', state: { from: this.props.location.pathname }}} />

history.push({
  pathname: '/graph/1',
  state: { 
      from: this.props.location.pathname
  }
})

然后你可以在你的组件中获取此位置,如this.props.location.state && this.props.location.state.from,然后决定是否要goBack

}

答案 1 :(得分:3)

使用 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>
}

然后,在 RouterProvider 下的某个组件中:

const route = useContext(RouterContext);

 //...
 <Link to={route.from}>
     Go Back
 </Link>

答案 2 :(得分:-2)

历史记录对象具有条目和当前索引。我以下列方式使用它们:

var lastLocation = history.entries[history.index - 1];
var lastUrl = lastLocation.pathname;