【问题标题】:React router and useCallback反应路由器和使用回调
【发布时间】:2020-10-22 05:53:04
【问题描述】:

我有以下路线:

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>
  }, []);

但是什么都没有发生,有没有人能够指导我了解我可能做错了什么?

【问题讨论】:

  • 这是一个 useCallback 而不是常规函数有什么具体原因吗?
  • 根据最佳实践我们应该使用useCallback。
  • 这取决于:)
  • 你能解释更多吗?有链接吗?
  • kentcdodds.com/blog/usememo-and-usecallback 他解释什么时候不该什么时候该

标签: reactjs typescript react-router


【解决方案1】:

这行不通,你想要的是以编程方式重定向。

为此,您应该这样做:

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

【讨论】:

    【解决方案2】:

    您正在做的事情将不起作用,因为Redirect 组件应该在 JSX 中呈现,以便它工作并更改路由。

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

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

      props.history.push('/estimates')
      

      你也可以使用 react 路由器提供的 useHistory 钩子来访问 history 对象。

    2. 使用 react 路由器提供的 Link 组件。它会自动改变路由而不需要点击监听器

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

    更多详情见:

    【讨论】:

      猜你喜欢
      • 2017-06-05
      • 2021-06-17
      • 1970-01-01
      • 2016-08-18
      • 2017-06-14
      • 2020-09-30
      • 2017-10-12
      • 2018-08-03
      • 2021-12-21
      相关资源
      最近更新 更多