【问题标题】:Type is invalid -- expected a string (for built-in components) or a class/function (for composite components) but got: <div />类型无效——需要一个字符串(对于内置组件)或一个类/函数(对于复合组件)但得到:<div />
【发布时间】:2021-12-26 17:27:00
【问题描述】:

我一直在尝试实现 React 框架,我收到了这个错误消息:

type is invalid -- expected a string (for built-in components) or a class/function (for composite components) but got: <div />. Did you accidentally export a JSX literal instead of a component?

除了部分,一切正常。

我已经尝试了以下。

  1. 检查没有拼写错误
  2. 进出口错误
  3. 在加载应用时显示替换字符串、“正在加载...”和“正在加载...”。

请帮帮我。

以下是我的代码

Weather.js

import React, { useState } from "react";
import WeatherInfo from "./WeatherInfo";
import WeatherForecast from "./WeatherForecast";
import "./Weather.css";
import axios from "axios";
import "react-loading-skeleton/dist/skeleton.css";
import SkeletonLoading from "./skeletons/SkeletonLoading";

export default function Weather(props) {
  const [city, setCity] = useState(props.defaultCity);
  const [weather, setWeather] = useState({ ready: false });

  function showWeather(response) {
    setWeather({
      ready: true,
      coordinates: response.data.coord,
      city: response.data.name,
     
    });
  }

  function handleSubmit(event) {
    event.preventDefault();
    search();
  }

  function updateCity(event) {
    setCity(event.target.value);
  }
  function search() {
    let apiKey = ``;
    let units = "metric";
    let apiUrl = `https://api.openweathermap.org/data/2.5/weather?q=${city}&appid=${apiKey}&units=${units}`;
    axios.get(apiUrl).then(showWeather);
  }

  if (weather.ready) {
    return (
      <div className="container">
        <form onSubmit={handleSubmit}>
          <input
            className="input-window"
            type="search"
            onChange={updateCity}
          />
          <input className="search-button" type="submit" value="Search" />
        </form>
        <WeatherInfo data={weather} />
        <hr />
        <WeatherForecast coordinates={weather.coordinates} />
      </div>
    );
  } else {
    search();
    <SkeletonLoading />;
  }
}

SkeletonLoading.js

import Skeleton from "react-loading-skeleton";
import "./SkeletonLoading.css";

const SkeletonLoading = () => {
  return (
    <div>
      <div className="skeleton-one">
        <Skeleton count={1} />
      </div>
    </div>
  );
};

export default SkeletonLoading();

【问题讨论】:

  • 嗯,错误消息实际上很清楚出了什么问题 - 您导出了一个文字(运行 SkeletonLoading 的结果)而不是 SkeletonLoading 组件本身。
  • 感谢您的清晰解释,raina77ow!我不确定错误消息是关于什么的,也无法指定 SkeletonLoading JSX 字面量的原因。现在问题已解决,骨架正在工作。

标签: javascript reactjs react-loading-skeleton


【解决方案1】:

导出时不要执行SkeletonLoading组件。

SkeletonLoading.js的最后一行替换为export default SkeletonLoading;

如果你执行组件,基本上它会导出函数/组件的返回值。在这种情况下是 JSX 文字。

【讨论】:

  • 感谢达斯学徒的明确回答和详细解释。现在问题解决了,骨架开始工作了!
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2022-01-12
  • 1970-01-01
  • 2020-11-01
  • 1970-01-01
  • 2020-09-04
  • 2020-03-07
相关资源
最近更新 更多