首页 > 解决方案 > 错误:应用程序(...):渲染没有返回任何内容。这通常意味着缺少返回语句 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");

标签: reactjstypescriptdiscord.js

解决方案


该错误是由您的 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>;
       }

推荐阅读