【问题标题】:Accessing state in functional component after redirect重定向后访问功能组件中的状态
【发布时间】:2020-01-02 00:09:06
【问题描述】:

<Redirect> 返回到另一个功能组件后,我似乎无法访问重定向到的组件中的carId 属性。我想知道过去是否有人解决过这个问题。

重定向将包含一个路径名“..\cars\cardetail\carId”,并另外包含一个状态属性:"state:{carId:xxx}"。但是,尽管我被重定向到正确的页面,但我似乎无法将 carId 从 Url 或 state 对象中提取出来。

【问题讨论】:

  • 你能贴出你试过的代码吗?沙盒上的最小示例会好得多?

标签: reactjs url redirect state prop


【解决方案1】:

而不是<Redirect> 使用

props.history.push({
    pathname: '..\cars\cardetail',
    state: {carId:xxx},          
  });

如果您收到“TypeError: Cannot read property 'push' of undefined”,请尝试以下操作。

由于最近的更改,现在路由道具不会被隐式传递。所以使用“useHistory”钩子

import { useHistory } from 'react-router-dom';
const history = useHistory();

history.push({
  pathname: '..\cars\cardetail',
  state: {carId:xxx},          
});

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2021-04-15
    • 1970-01-01
    • 1970-01-01
    • 2021-01-14
    • 2022-11-21
    • 1970-01-01
    • 1970-01-01
    • 2021-01-19
    相关资源
    最近更新 更多