Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/solr/3.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Reactjs 如何在渲染函数外部调用react router 4重定向?_Reactjs_React Router V4 - Fatal编程技术网

Reactjs 如何在渲染函数外部调用react router 4重定向?

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

我正在尝试使用RR4以编程方式导航。保存一些数据后,我想呈现一个
重定向
,如下所示:

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>
  );
}