【问题标题】:Router push not working from within useEffect hook路由器推送在 useEffect 挂钩中不起作用
【发布时间】:2021-11-15 21:19:15
【问题描述】:

我有以下组件,我希望通过router's push method immediately cos router push is inside the useEffect` 挂钩转到另一条路径。

但路由器推送似乎从未发生过。 ShowLoading 组件只是一个加载屏幕(显示加载微调器)。

页面只是停留在加载微调器屏幕上。

我做错了什么,为什么我没有被推送到新页面?请建议。谢谢。

import React from 'react';
import Cookies from 'js-cookie';
import { ShowLoading } from '../../ShowLoading';
import { withRouter } from 'react-router';

const MyComponent = ({
  router: { push, location },
}) => {
  React.useEffect(() => {    
    // this cookie gets set thus clearly we are entering this useEffect. 
    Cookies.set('temp', '1');

    const value = 'test';
    const params = location.search ? `${location.search}` : '';

    // seems like this has no effect, no pushing and moving to new page path. 
    push(`/${value}/my_path${params}`);

  }, []);
  return (<ShowLoading />);
};

export default (withRouter(MyComponent);

P.S:如果我执行以下操作但希望通过路由器执行此操作,则会按预期进入新路径。

window.location.pathname = `/${value}/my_path${params}`;

【问题讨论】:

    标签: javascript reactjs react-hooks react-router


    【解决方案1】:

    在使用withRouter 时,您可以获得matchhistorylocation 作为道具。所以你可以像这样得到history的推送:

    import React from 'react';
    import Cookies from 'js-cookie';
    import { ShowLoading } from '../../ShowLoading';
    import { withRouter } from 'react-router';
    
    const MyComponent = ({
      history,
      location
    }) => {
      React.useEffect(() => {    
        // this cookie gets set thus clearly we are entering this useEffect. 
        Cookies.set('temp', '1');
    
        const value = 'test';
        const params = location.search ? `${location.search}` : '';
    
        history.push(`/${value}/my_path${params}`);
    
      }, []);
      return (<ShowLoading />);
    };
    
    export default withRouter(MyComponent);
    

    【讨论】:

    • 如果我这样做,微调器会停止,但我会停留在同一页面上。由于某种原因,我也不再设置 cookie。
    • params 值是否与您要查找的值相对应?尝试在控制台上记录它
    • 我目前实际上在同一条路径上,例如 - /value/my_path?param=1。从这里开始,我只想再次回到相同的路径 - /value/my_path?param=1。类似于刷新,由于设置了 cookie,现在由于刷新而发生了一些其他操作。
    • window.location.pathname = ... 适用于此刷新。但是我因此而失去了一些跟踪值,因此尝试使用 React Router。
    • 哦,你只是想刷新页面??试试 history.go(0) 你也可以查看这个部分以获得可能的答案stackoverflow.com/questions/46820682/…
    猜你喜欢
    • 2021-09-22
    • 2021-11-14
    • 2023-02-24
    • 2021-04-13
    • 1970-01-01
    • 2021-02-13
    • 2021-07-11
    • 1970-01-01
    • 2018-10-10
    相关资源
    最近更新 更多