Reactjs 路由器不会在函数内重定向

Reactjs 路由器不会在函数内重定向,reactjs,celery,Reactjs,Celery,我正在创建一个跟踪芹菜背景作业状态的函数。 基本上,如果未完成,后台作业将向前端发送一个JSON,其中包含单词PENDING,如果完成,则发送SUCCESS。 我通过调用setTimeout每秒检查JSON是否已更改 但是,当函数进入else语句时,我会在控制台console.log(“redirect”)中打印出来,但它不会执行代码:return 由于我试图在if-else语句外部重定向,因此路由工作正常 我不知道为什么它没有重定向 function MyComponent() { ...

我正在创建一个跟踪芹菜背景作业状态的函数。 基本上,如果未完成,后台作业将向前端发送一个JSON,其中包含单词
PENDING
,如果完成,则发送
SUCCESS
。 我通过调用
setTimeout
每秒检查JSON是否已更改

但是,当函数进入else语句时,我会在控制台
console.log(“redirect”)
中打印出来,但它不会执行代码:
return

由于我试图在
if-else
语句外部重定向,因此路由工作正常

我不知道为什么它没有重定向

function MyComponent() {
...
    function updateProgress(statusUrl) {
        const celeryStatus = fetch(statusUrl)
            .then(response => response.json())
            .then(jsonData => {checkStatus(jsonData, statusUrl)})
    }

    function checkStatus(jsonData, statusUrl) {
        if (jsonData.state === "PENDING") {
            console.log("inside pending")

            setTimeout(function() {
                updateProgress(statusUrl);
            }, 1000);
        } else {
            console.log("redirect")
            return <Redirect to={{pathname: '/dashboard/'}}/>
        }
    }
# Calling the functions
return ...
}
函数MyComponent(){
...
函数updateProgress(状态URL){
const celeryStatus=fetch(statusUrl)
.then(response=>response.json())
.then(jsonData=>{checkStatus(jsonData,statusUrl)})
}
函数检查状态(jsonData、statusUrl){
if(jsonData.state==“待定”){
console.log(“内部挂起”)
setTimeout(函数(){
updateProgress(statusUrl);
}, 1000);
}否则{
console.log(“重定向”)
返回
}
}
#调用函数
返回。。。
}

您正在从一个不呈现任何内容的函数返回组件,重定向组件应该放在render()方法或函数组件中

如果这是反应路由器

import { useHistory } from 'react-router';
然后,以编程方式导航

const history = useHistory();
if(someCondition){
   history.push('/somewhere');
}

当您从一个不呈现任何内容的函数返回组件时,重定向组件应该放在render()方法或函数组件中

如果这是反应路由器

import { useHistory } from 'react-router';
然后,以编程方式导航

const history = useHistory();
if(someCondition){
   history.push('/somewhere');
}

您可以尝试使用下面的


      this.props.history.push({
        pathname: '/dashboard',
      })


您可以尝试使用下面的


      this.props.history.push({
        pathname: '/dashboard',
      })


因为组件默认值在props对象上有历史记录,所以他不能只使用
this.props吗?我应该把它放在组件中还是放在组件内部的函数中?只要钩子在组件内部被调用,这并不重要。我不确定这个。props,因为我从来没有尝试过。他不能只使用
这个。props,因为组件默认值在props对象上有历史记录吗?我应该把它放在组件中还是放在组件内部的函数中?只要钩子在组件内部被调用,这并不重要。我不确定这是不是道具,因为我从来没有试过。