【发布时间】: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);
所以问题是,它会在控制台中触发“hi2”,但不会重定向。
【问题讨论】:
-
从setTimeout返回其实没多大用,可以用
useHistory也一样, -
我很确定
Redirect仅在您实际渲染Redirect时才有效。尝试使用 history 属性并将路由推送到历史堆栈。 -
@KyleLambert 你是对的
标签: reactjs redux react-redux react-router