我刚刚把react-router从v3替换为v4。 但我不确定如何以编程方式在组件的成员函数中导航。 即在handleClick()函数中,我想在处理一些数据后导航到/path/some/where。 我以前是这样做的:
import { browserHistory } from 'react-router'
browserHistory.push('/path/some/where')
但是我在v4中找不到这样的界面。 如何使用v4导航?
我刚刚把react-router从v3替换为v4。 但我不确定如何以编程方式在组件的成员函数中导航。 即在handleClick()函数中,我想在处理一些数据后导航到/path/some/where。 我以前是这样做的:
import { browserHistory } from 'react-router'
browserHistory.push('/path/some/where')
但是我在v4中找不到这样的界面。 如何使用v4导航?
当前回答
最简单的方法是:
this.props.history.push(“/new/url”)
注意:
如果历史道具不可用,你可以将它从父组件传递到你想调用该动作的组件。
其他回答
你可以通过这种方式有条件地导航
import { useHistory } from "react-router-dom";
function HomeButton() {
const history = useHistory();
function handleClick() {
history.push("/path/some/where");
}
return (
<button type="button" onClick={handleClick}>
Go home
</button>
);
}
我认为@rgommezz涵盖了大多数情况,除了一个我认为非常重要的情况。
// history is already a dependency or React Router, but if don't have it then try npm install save-dev history
import createHistory from "history/createBrowserHistory"
// in your function then call add the below
const history = createHistory();
// Use push, replace, and go to navigate around.
history.push("/home");
这允许我写一个简单的服务与动作/调用,我可以调用从任何组件做导航,而不需要在我的组件上做很多HoC…
目前还不清楚为什么以前没有人提供这种解决方案。我希望它能有所帮助,如果你看到任何问题,请告诉我。
我已经测试v4好几天了。到目前为止,我很喜欢它!过一段时间就明白了。
我也有同样的问题,我发现用下面的方法处理它是最好的(甚至可能是它的目的)。它使用state、三元操作符和<Redirect>。
在构造函数()中
this.state = {
redirectTo: null
}
this.clickhandler = this.clickhandler.bind(this);
在render()中
render(){
return (
<div>
{ this.state.redirectTo ?
<Redirect to={{ pathname: this.state.redirectTo }} /> :
(
<div>
..
<button onClick={ this.clickhandler } />
..
</div>
)
}
在clickhandler()中
this.setState({ redirectTo: '/path/some/where' });
希望能有所帮助。让我知道。
由于没有其他方法来处理这个可怕的设计,所以我编写了一个使用withRouter HOC方法的通用组件。下面的例子是包装一个按钮元素,但你可以更改为任何你需要的可点击元素:
import React from 'react';
import PropTypes from 'prop-types';
import { withRouter } from 'react-router-dom';
const NavButton = (props) => (
<Button onClick={() => props.history.push(props.to)}>
{props.children}
</Button>
);
NavButton.propTypes = {
history: PropTypes.shape({
push: PropTypes.func.isRequired
}),
to: PropTypes.string.isRequired
};
export default withRouter(NavButton);
用法:
<NavButton to="/somewhere">Click me</NavButton>
你也可以简单地使用props来访问历史对象: