【问题标题】:Why is react-router-dom <Redirect> not working?为什么 react-router-dom <Redirect> 不起作用?
【发布时间】:2021-03-15 18:26:54
【问题描述】:

只是尝试在经过身份验证后简单地重定向。想我会将我的登录屏幕转换为类组件,因为我有一个重定向的条件导致无限循环。但是,一旦我转换了登录屏幕,重定向就根本不起作用。我正在使用 react-router-dom v5.2 ...我读到有人说重定向不是 v5+ 的一部分,它更改为“导航”...但它肯定在某个时候起作用。而且当尝试使用“导航”时,它说它不是一个导出的包。

这里是登录屏幕:

class LoginScreen extends React.Component {
    constructor(props) {
        super(props)
        this.state = {
            username: '',
            password: '',
            password2: '',
            role: '',
            email: ''
        }
    }

    componentDidUpdate() {
        if (this.props.isAuthenticated) {
            console.log("Logged in")
            return (<Redirect to={'/dashboard'} />)
        }
    }

    render() {
        const { email, role, password, password2, username } = this.state
        return (
            <$.Container>
                <$.Wrapper>
                    <$.Logo />
                    <$.Form>
                        <$.Input
                            type="email"
                            value={email}
                            placeholder="Email"
                            onChange={e => this.setState({ email: e.target.value })}
                        />
                        <$.Input
                            type="username"
                            value={username}
                            placeholder="Username"
                            onChange={e => this.setState({ username: e.target.value })}
                        />
                        <$.Input
                            type="password"
                            value={password}
                            placeholder="Password"
                            onChange={e => this.setState({ password: e.target.value })}
                        />
                        <$.Input
                            type="password"
                            value={password2}
                            placeholder="Password Confirm"
                            onChange={e => this.setState({ password2: e.target.value })}
                        />
                        <$.Input
                            type="role"
                            value={role}
                            placeholder="Role"
                            onChange={e => this.setState({ role: e.target.value })}
                        />
                    </$.Form>
                    <$.Button onClick={() => this.props.login(email, password)}>Sign In</$.Button>
                    <$.Button onClick={() => this.props.register({ email, password, password2, role, username })}>Register</$.Button>

                    {this.props.message != null ?
                        this.props.error ?
                            <$.Error>{this.props.message}</$.Error>
                            : <$.Info>{this.props.message}</$.Info>
                        : null}
                </$.Wrapper>
            </$.Container >
        )
    }
}

const mapStateToProps = ({ auth }) => {
    const { isAuthenticated, message, error } = auth
    return { isAuthenticated, message, error }
}

const mapDispatchToProps = { login, register }

export default connect(mapStateToProps, mapDispatchToProps)(LoginScreen)

条件通过,因为日志语句被输出。但重定向不是重定向。

这里是 app.js 渲染:

<Provider store={store}>
  <Router>
    <div className="App">
      <Switch>
        {routes.map((route, index) => (
          route.private ?
            <PrivateRoute exact={route.exact} path={route.path} component={route.main} key={index} />
            :
            <Route exact={route.exact} path={route.path} component={route.main} key={index} />))}
      </Switch>
    </div>
  </Router>
</Provider>

页面重定向到:

import React from 'react'

function DashboardScreen(props) {
  return (
    <div>
      <h1>dashboard screen</h1>
    </div>
  )
}

export default DashboardScreen

privateRoute 组件:

import React from 'react'
import { connect } from 'react-redux'
import { Route, Redirect } from 'react-router-dom'
import Sidebar from '../components/navigation/Sidebar'

function PrivateRoute({ component: Component, ...rest }) {

    return (
        <Route {...rest} render={(props) => props.isAuthenticated ? (
            <div style={{ display: 'grid', gridTemplateColumns: '200px auto' }}>
                <Sidebar role={'super-admin'} />
                <Component role={'test-role'} {...props} />
            </div>
        ) : (
                <Redirect to={{ pathname: '/', state: { referrer: props.location } }} />
            )}
        />
    )
}

const mapStateToProps = ({ auth }) => {
    const { isAuthenticated } = auth
    return { isAuthenticated }
}

export default connect(mapStateToProps)(PrivateRoute)

我怎样才能让这个重定向工作?

【问题讨论】:

    标签: reactjs react-router-dom


    【解决方案1】:

    您需要将Redirect 放入要呈现的JSX 中。 componentDidUpdate 不会呈现该返回值。因此,请删除 componentDidUpdate 并将 render 的顶部更改为:

        render() {
            const { isAuthenticated } = this.props;
            const { email, role, password, password2, username } = this.state;
    
            if (isAuthenticated) {
                return (<Redirect to={'/dashboard'} />);
            }
    
            return (
                ...
    

    【讨论】:

    • 完成此操作后,我收到Error: Maximum update depth exceeded... 错误
    • 听起来你有一个重定向循环。您显示的组件是否在/dashboard 上呈现?如果是这样,那可能就是问题所在。或者它可能是/dashboard 也有一个Redirect?没有所有细节就很难调试这样的循环。
    • 我不认为我做了,但我会更深入地看看
    • 我添加了重定向到的屏幕和私有路由组件。我没有看到循环...
    • @Jim 不幸的是,您遇到的事情足够复杂,以至于您必须发布一个完整的示例。我怀疑您以某种方式在其他地方呈现登录屏幕。根据我上面的回答,您可以尝试将返回值更改为 return (&lt;div&gt;I'd redirect now&lt;/div&gt;); 并查看是否会改变行为(如果您在 /dashboard 上看到它 - 我会检查 DOM)。
    猜你喜欢
    • 2020-10-13
    • 2018-01-28
    • 2020-07-31
    • 2018-07-31
    • 1970-01-01
    • 2022-06-16
    • 2020-01-30
    • 2021-02-25
    • 1970-01-01
    相关资源
    最近更新 更多