首页 > 解决方案 > 如果未在承诺中验证重定向和 setState

问题描述

我有:

import React, {Component} from 'react';
import ReactDOM from 'react-dom';
import PropTypes from "prop-types";
import {Router, Route, Switch} from 'react-router-dom'
import { Redirect } from "react-router";
import history from './History';


import Home from '../containers/Home';
import Login from '../containers/LogIn';
import CreateUsers from '../containers/CreateUsers';
import Dashboard from '../containers/Dashboard';
import NavBar from './NavBar';

class App extends Component {

    constructor(props) {
        super(props);

        this.state = {
            isAuthenticated: false
        };

        fetch("/api/user")
            .then(function (response) {
                return response.json();
            })
            .then(function (res) {
                console.log(res);
                if (res.enabled === 1) {
                    this.setState({
                        isAuthenticated: true
                    });
                    // Redirect the user only if they are on the login page.
                    history.push("/dashboard");
                } else {
                    history.push("/login");
                }
            });
    }

    componentDidMount() {

    }

    render() {
        return (
            <Router history={history}>
                <div>
                    <NavBar />
                    <Route>
                        <Redirect from="/" to="/login" /> // If not authenticated, how???
                    </Route>
                    <Route path="/login" component={Login}/>
                    <Route path="/dashboard" component={Dashboard}/>
                </div>
            </Router>
        )
    }
}

ReactDOM.render(<App />, document.getElementById('app'))

我有两个问题,第一个是如果用户身份验证失败,我如何让它使用路由器重定向回登录,目前我收到错误:React.Children.only expected to receive a single React element child

另一个问题是它无法this从以下位置看到:

.then(function (res) {
                console.log(res);
                if (res.enabled === 1) {
                    this.setState({
                        isAuthenticated: true
                    });
...

给我Uncaught (in promise) TypeError: Cannot read property 'setState' of undefined

标签: javascriptreactjs

解决方案


您的初始代码将与稍作更改后的代码相同。在做出承诺之前,将其放入如下变量中 -

让我=这个;

当你承诺完成并且你正在更新状态时,使用如下 -

me.setState({ isAuthenticated: true });

它会正常工作。


推荐阅读