反应路由器和useCallback

时间:2020-07-01 17:52:48

标签: reactjs typescript react-router

我有以下路线:

const makeIndexRoutes = (): React.ReactElement => (
  <Switch>
    <Redirect exact from="/" to="/estimates" />
    <Route exact path="/estimates" component={CostingPage} />
    <Route exact path="/estimates/new" component={NewEstimatePage} />
    <Route exact path="/estimates/edit/:id" component={EditEstimatePage} />
  </Switch>
);

在另一个文件中,我尝试像这样在按钮单击上进行重定向:

  const handleClose = useCallback(() => {
    // do some action on 'close' button click
    <Redirect to='/estimates'></Redirect>
  }, []);

但是什么也没发生,有人能指导我解决我可能做错的事情吗?

2 个答案:

答案 0 :(得分:1)

这行不通,您需要以编程方式重定向。

为此,您应该执行以下操作:

import { useHistory } from 'react-router-dom';
const history = useHistory();
const handleClose = () => {
  history.push('/estimates');
});

答案 1 :(得分:1)

您正在做的事情将无法正常工作,因为Redirect组件应在JSX中呈现,以便其工作并更改路线。

您可以使用以下选项之一更改路线

  1. 使用路由器道具中的history对象

    props.history.push('/estimates')
    

    您还可以使用React Router提供的useHistory钩子来访问history对象。

  2. 使用React路由器提供的Link组件。它将自动更改路线,而无需点击侦听器

    <Link to="/estimates">Estimates</Link>
    

有关更多详细信息,请参见:

相关问题