在React中,可以使用useHistory
hook来获取history
对象,并使用push
方法进行导航。要保留初始的props.history.location.pathname
并从那里导航,可以在组件中使用useState
hook来保存初始的pathname,然后在导航时使用该值。
以下是一个示例代码:
import React, { useState } from 'react';
import { useHistory } from 'react-router-dom';
const MyComponent = (props) => {
const history = useHistory();
const [initialPathname, setInitialPathname] = useState(props.history.location.pathname);
const navigateToInitialPathname = () => {
history.push(initialPathname);
};
return (
);
}
export default MyComponent;
在上面的示例中,我们使用useState
hook来保存初始的props.history.location.pathname
。然后,我们使用useHistory
hook获取history
对象,并在navigateToInitialPathname
函数中使用push
方法导航到初始的pathname。在组件中,我们使用一个按钮来触发导航操作。
请注意,上述示例假设你已经设置了React Router的路由配置,并且将MyComponent
组件包装在
或
组件中。确保在正确的上下文中使用useHistory
hook。
希望这可以帮助到你!