【问题标题】:setTimeout fires but does not redirectssetTimeout 触发但不重定向
【发布时间】:2021-04-11 03:19:12
【问题描述】:

我创建了一个 404 Not Found 组件,我想在 3 秒后重定向用户,具体取决于用户是否登录。那是通过isAuthenticated state 进行检查。

这是我的NotFound.js 组件;

import React, { Fragment } from 'react';
import notfound from '../../img/404.svg';
import { useEffect } from 'react';
import { Redirect } from 'react-router-dom';
import PropTypes from 'prop-types';
import { connect } from 'react-redux';

const NotFound = ({ auth: { isAuthenticated } }) => {
 const styles = {
  width: 'calc(100% - 100px)',
  height: '600px',

  position: 'relative',
  top: '200px',
  marginBottom: '150px',
 };
 useEffect(() => {
    setTimeout(() => {
      if (isAuthenticated) {
        console.log('hi');
      return <Redirect to='/adverts'></Redirect>;
    } else if (!isAuthenticated) {
       console.log('hi2');
     return <Redirect to='/'></Redirect>;
    }
  }, 3000);
});


  return (
      <Fragment>
        <img src={notfound} style={styles}></img>
    </Fragment>
   );
 };

 NotFound.propTypes = {
    auth: PropTypes.object,
 };

 const mapStateToProps = (state) => ({
    auth: state.auth,
 });

 export default connect(mapStateToProps)(NotFound);

这里是console.log;

所以问题是,它会在控制台中触发“hi2”,但不会重定向。

【问题讨论】:

  • 从setTimeout返回其实没多大用,可以用useHistory也一样,
  • 我很确定 Redirect 仅在您实际渲染 Redirect 时才有效。尝试使用 history 属性并将路由推送到历史堆栈。
  • @KyleLambert 你是对的

标签: reactjs redux react-redux react-router


【解决方案1】:

尝试使用useHistory

import { useHistory } from "react-router-dom";

const NotFound = ({ auth: { isAuthenticated } }) => {
  const history = useHistory()
  useEffect(() => {
    setTimeout(() => {
      if (isAuthenticated) {
        console.log('hi');
      history.push('/adverts')
    } else if (!isAuthenticated) {
      console.log('hi2');
      history.push('/')
    }
    }, 3000);
  });

  ...
}

【讨论】:

  • 我现在明白了,我应该使用历史记录而不是直接渲染重定向。谢谢!
  • 您可以在渲染模板中使用redirect。看看这个answer,这将帮助你理解重定向渲染的概念
【解决方案2】:

您应该将&lt;Redirect /&gt;条件渲染作为return 语句的一部分。

更多详细答案请查看How to use Redirect in the new react-router-dom of Reactjs

【讨论】:

    【解决方案3】:

    这是因为setTimeout 回调函数不是NotFound 组件返回语句的一部分。

    如果你需要使用Redirect 组件你需要做这样的事情:

    const [redirect, setRedirect] = useState(null);
    useEffect(() => {
        setTimeout(() => {
          if (isAuthenticated) {
            console.log('hi');
            setRedirect('/adverts')
        } else if (!isAuthenticated) {
           console.log('hi2');
            setRedirect('/')
        }
      }, 3000);
    });
    
    if(redirect){
      return <Redirect to={redirect} />
    }
    
    return <>...</>
    
    //+++++++++++++++++++
    //or use history object like this:
    
    const history = useHistory();
    useEffect(() => {
        setTimeout(() => {
          if (isAuthenticated) {
            console.log('hi');
            history.push('/adverts')
        } else if (!isAuthenticated) {
           console.log('hi2');
            history.push('/')
        }
      }, 3000);
    });
    
    return <>...</>
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2023-03-14
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多