javascript - 如果未在承诺中验证重定向和 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
解决方案
您的初始代码将与稍作更改后的代码相同。在做出承诺之前,将其放入如下变量中 -
让我=这个;
当你承诺完成并且你正在更新状态时,使用如下 -
me.setState({ isAuthenticated: true });
它会正常工作。
推荐阅读
- php - 使用 Behat 和 Selenium2 驱动程序运行测试失败,因为 DevToolsActivePort 文件不存在
- wpf - 如何在新窗口中重现 MessageBox 的相同布局?
- html - 我希望导航栏中的项目均匀水平。#HTML #CSS
- python - OrderedDict 和 dict 的键顺序是否相同?
- r - 在 Rstudio 中对大型数据框进行 Wilcox 测试
- java - 如何将带有图片的文件从应用程序发送到电子邮件或 whatsapp (25.10.2021)
- java - 需要一种方法来获取与 List.stream().anyMatch() 匹配的字符串中的模式
- javascript - javascript输出中的箭头函数?
- jmeter - JMeter - websocket插件 - 禁止错误
- import - 加载本地图像 React