Reactjs React-api调用后重定向不起作用

Reactjs React-api调用后重定向不起作用,reactjs,Reactjs,我正在尝试从react router dom使用重定向 因此,在发出API post请求后,如果成功,我想返回主页 有什么想法吗?以下有什么问题吗 try { const resp = await axios.post('http://localhost:8080/add', page); if (resp.status == 200) { return <Redirect to="/" /> } } c

我正在尝试从
react router dom
使用
重定向

因此,在发出API post请求后,如果成功,我想返回主页

有什么想法吗?以下有什么问题吗

try {
      const resp = await axios.post('http://localhost:8080/add', page);
      if (resp.status == 200) {
        return <Redirect to="/" />
      }
    } catch (err) {
      console.log(err);
    }
当我收到错误时:
error:Invariant失败:您不应该在


谢谢。

您可能需要使用
setState
来更改状态,并在
渲染中重定向

class MyComponent extends React.Component {
  state = {
    redirect: false
  }

  async foo () {
    try {
      const resp = await axios.post('http://localhost:8080/add', page);
      if (resp.status == 200) {
        this.setState({redirect:true})
      }
    } catch (err) {
      console.log(err);
    }

  }

  render () {
    const { redirect } = this.state;

     if (redirect) {
       return <Redirect to='/'/>;
     }

    ...
}
类MyComponent扩展了React.Component{ 状态={ 重定向:false } 异步foo(){ 试一试{ const resp=等待axios.post('http://localhost:8080/add,第页); 如果(各自状态==200){ this.setState({redirect:true}) } }捕捉(错误){ 控制台日志(err); } } 渲染(){ const{redirect}=this.state; 如果(重定向){ 返回; } ... }
或者,您可以尝试使用
历史记录
谢谢-是的,我读过类似的内容,但我仍然收到一个错误-我更新了我的问题..我希望
路由器
包含了您的组件,它是-但是我现在看到错误
无法读取未定义的属性
的“位置”,然后是
警告:失败的属性类型:道具
history`在
Router
中按要求标记,但其值是
未定义的
`啊-它必须是
浏览器路由器
所以
谢谢你的帮助。很好,干杯,伙计:D
class MyComponent extends React.Component {
  state = {
    redirect: false
  }

  async foo () {
    try {
      const resp = await axios.post('http://localhost:8080/add', page);
      if (resp.status == 200) {
        this.setState({redirect:true})
      }
    } catch (err) {
      console.log(err);
    }

  }

  render () {
    const { redirect } = this.state;

     if (redirect) {
       return <Redirect to='/'/>;
     }

    ...
}