我有以下组件,我希望通过router's push method immediately cos router push is inside the
useEffect '钩子转到另一个路径。
但是router push似乎从来没有发生过。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}`;
使用withRouter
时可以得到match
,history
和location
作为道具。所以你可以像这样从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);