Reactjs 如何在渲染函数外部调用react router 4重定向?
我正在尝试使用RR4以编程方式导航。保存一些数据后,我想呈现一个Reactjs 如何在渲染函数外部调用react router 4重定向?,reactjs,react-router-v4,Reactjs,React Router V4,我正在尝试使用RR4以编程方式导航。保存一些数据后,我想呈现一个重定向,如下所示: handleSave = () => { this.props.mutate({ ... }); this.setState({ org: null }); <Redirect to="/orgs" /> // return <Redirect to="/orgs" /> // Tried this
重定向
,如下所示:
handleSave = () => {
this.props.mutate({
...
});
this.setState({
org: null
});
<Redirect to="/orgs" />
// return <Redirect to="/orgs" /> // Tried this also
};
这是我想要的,但我不喜欢三元语句。有没有一种方法可以像我在第一个示例中尝试的那样,将
重定向
添加到save函数中?使用历史
道具
和推送
或替换
方法。每个路由都会获得它,但是您也可以使用with router
HOC将其注入其他组件
医生。
这个答案有很多好的信息和例子: 与路由器一起使用 这对我来说非常有效:
import { useHistory } from "react-router-dom";
function HomeButton() {
const history = useHistory();
function handleClick() {
history.push("/home");
}
return (
<button type="button" onClick={handleClick}>
Go home
</button>
);
}
从“react router dom”导入{useHistory};
函数HomeButton(){
const history=useHistory();
函数handleClick(){
历史推送(“/主页”);
}
返回(
回家吧
);
}
正如我所注意到的,在渲染函数中有push/>,而在handlesave函数中没有。还有一件事-您是否检查了handleSave()函数是否正在调用。handleSave
是否正在被调用。我试过使用推送/不使用推送。是的,我肯定会使用withRouter
来做这个.prop.router.push
import { useHistory } from "react-router-dom";
function HomeButton() {
const history = useHistory();
function handleClick() {
history.push("/home");
}
return (
<button type="button" onClick={handleClick}>
Go home
</button>
);
}