reactjs - 错误:应用程序(...):渲染没有返回任何内容。这通常意味着缺少返回语句 discord.js react typescript
问题描述
我可以不和谐 oauth2 typescript & react 但我遇到了这个错误。我不知道如何解决它。能否请你帮忙?它会在我输入的地址不断更新我,请帮助我解决这个问题。
import React, { Component } from "react";
import { BrowserRouter as Router, Route } from "react-router-dom"
import fetch from "node-fetch";
import NavigationBar from "./navigation/NavigationBar";
import ServerSelection from "../pages/ServerSelection";
export default class App extends Component {
state = {
loading: true,
user: null
}
componentDidMount() {
fetch("http://192.168.1.34:8080/oauth/details", {
credentials: "include"
})
.then(res => res.json())
.then(res => {
if (!res) return this.setState({ loading: false });
this.setState({
loading: false,
user: res
})
})
.catch(() => this.setState({ loading: false }));
}
render() {
if (this.state.loading) {
return (
<React.Fragment>
<div className="container">
<h1>Loading...</h1>
</div>
</React.Fragment>
);
} else if (!this.state.user) {
window.location.replace("http://192.168.1.34:8080/oauth/login");
解决方案
该错误是由您的 render() 方法未返回任何组件引起的。
你的渲染方法中有一个 if 和 else-if 块,但是如果这两个条件都失败了怎么办?你的 render() 方法应该有一个最终的 return 语句或一个 else 块。
错误是由这一行引起的:
.catch(() => this.setState({ loading: false }));
因此,当您的 fetch 遇到错误时,它会将 loading 设置为 false,然后当您的组件尝试渲染时,会发生这种情况:
if (this.state.loading)
加载为假,因此条件失败
this.setState({
loading: false,//loading was set to false
user: res
})
此条件也失败,因为您已为 state.user 分配了一个值
.then(res => {
if (!res) return this.setState({ loading: false });
this.setState({
loading: false,
user: res//user is also not falsey
})
解决方案是添加最终的 return 语句:
render() {
if (this.state.loading) {
return (
<React.Fragment>
<div className="container">
<h1>Loading...</h1>
</div>
</React.Fragment>
);
} else if (!this.state.user) {
window.location.replace("http://192.168.1.34:8080/oauth/login");
return <p>EMPTY USER</p>;
}
return <p>CONDITIONS FAILED</p>;
}
推荐阅读
- c# - 对矩阵中的选定数字求和
- tensorflow - 将 SageMaker 管道模式与 tfrecords 的 s3 目录一起使用
- javascript - 通过键入添加前缀/后缀
- oauth-2.0 - 在 PKCE 的令牌响应中返回的所有额外属性有什么意义
- ads - 来自 Ads Analytics 的推广指标为空
- jsf - Primefaces 在关闭通知栏后删除它
- c# - Xamarin:如何重用标签和条目以避免创建大量类
- java - 如何在方法之间共享变量?
- c++ - 使用主线程在 QThread 中创建的失败连接对象和一个 QThread 中的失败连接 beetwen 对象
- java - 如何在 Java 中使用 ZXING 获取扫描的 QR 码的图像?#667