我刚刚将react-router
从v3替换为v4。
但是我不确定如何以编程方式在Component
的成员函数中导航。也就是说,在handleClick()
函数中,我想在处理完一些数据后导航到/path/some/where
。我过去常常这样做:
import { browserHistory } from 'react-router'
browserHistory.push('/path/some/where')
但我在v4中找不到这样的接口。
如何使用v4导航?
发布于 2019-10-02 06:25:56
如果使用的是函数组件,则使用useHistory
挂钩
您可以使用useHistory
钩子来获取history
实例。
import { useHistory } from "react-router-dom";
const MyComponent = () => {
const history = useHistory();
return (
<button onClick={() => history.push("/about")}>
Click me
</button>
);
}
useHistory
钩子允许您访问可用于导航的历史记录实例。
在页面组件中使用history
属性
React Router向页面组件注入了一些属性,包括history
。
class HomePage extends React.Component {
render() {
const { history } = this.props;
return (
<div>
<button onClick={() => history.push("/projects")}>
Projects
</button>
</div>
);
}
}
包装子组件withRouter
以注入路由器属性
withRouter
包装器将路由器属性注入组件。例如,您可以使用此包装器注入放置在用户菜单中的注销按钮组件。
import { withRouter } from "react-router";
const LogoutButton = withRouter(({ history }) => {
return (
<button onClick={() => history.push("/login")}>
Logout
</button>
);
});
export default LogoutButton;
发布于 2017-05-20 06:35:59
您还可以简单地使用props来访问历史对象:this.props.history.push('new_url')
发布于 2017-09-29 23:11:04
步骤1:上面只有一件事要导入:
import {Route} from 'react-router-dom';
步骤2:在你的路由中,传递历史记录:
<Route
exact
path='/posts/add'
render={({history}) => (
<PostAdd history={history} />
)}
/>
步骤3:在下一个组件中,历史记录被接受为属性的一部分,因此您可以简单地:
this.props.history.push('/');
这很简单,而且非常强大。
https://stackoverflow.com/questions/42123261
复制相似问题