簡體   English   中英

'Home' 不能用作 JSX 組件。 使用反應 typescript

[英]'Home' cannot be used as a JSX component. using react typescript

I am new to react and typescript,i want to fetch data from an api into a table using typescript and react.i have two files Home.tsx and App.tsx.the major code that has the api is contained in Home.tsx and另一個在 App.tsx 中。下面是錯誤消息,我得到'Home' cannot be used as a JSX component. Its return type 'void' is not a valid JSX element. 'Home' cannot be used as a JSX component. Its return type 'void' is not a valid JSX element. 這是 Home.tsx

import React, { useEffect, useState } from "react";
import styled from "styled-components";
import { Route, Router } from "react-router-dom";
//import  styledComponents from "styled-components";

// Could not find a declaration file for module 'styled-components'. '/var/www/html/public_html/react_js/myapp_task/node_modules/styled-components/dist/styled-components.cjs.js' implicitly has an 'any' type.
//   Try `npm i --save-dev @types/styled-components` if it exists or add a new declaration (.d.ts) file containing `declare module 'styled-components';`

import backgroundImage from "./background.png";

const Home = () => {
  const [users, setUsers] = useState<YourUserType[]>([]);
  //const [users, setUsers] = useState("");

  useEffect(() => {
    const url = "https://jsonplaceholder.typicode.com/users";

    const fetchData = async () => {
      try {
        const response = await fetch(url);
        const json = await response.json();
        console.log(json.slip.users);
        setUsers(json.slip.users);
      } catch (error) {
        console.log("error", error);
      }
    };

    fetchData();
  }, []);
//type Users = typeof users
      //type Users = typeof users {
     type YourUserType = {
        id: string,
        name: string,
        username: {
            slug: string
        },
        email: string,
        address: string,
    }

    const Table = ({ users }: { users: YourUserType[] }) => {

        return ( 
            <table>
              <thead>
                <tr>
                  <th>Id</th>
                  <th>Name</th>
                  <th>Username</th>
                  <th>Email</th>
                  <th>Address</th>
                </tr>
              </thead>
              <tbody>
                {users.length > 0 ? (

                    users.map((user, idx) => {
                   return (
                    <tr key={idx}>
                      <td>{ user.id }</td>
                      <td>{ user.name }</td>
                      <td>{ user.username.slug}</td>
                      <td>{ user.email}</td>
                      <td>{ user.address}</td>
                    </tr>
                  )
                 })) : <tr><td>Loading...</td></tr> }
              </tbody>
            </table>
        );
    }
}
export default Home;

const Wrapper = styled.div`
  padding-top: 150px;
  margin: 0 auto;
`;

const Title = styled.h1`
  font-family: -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, Oxygen,
    Ubuntu, Cantarell, "Open Sans", "Helvetica Neue", sans-serif;
  font-style: normal;
  font-weight: bold;
  font-size: 40px;
  line-height: 48px;
  color: #ffffff;
  text-align: center;
`;

const Description = styled.h2`
  font-family: -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, Oxygen,
    Ubuntu, Cantarell, "Open Sans", "Helvetica Neue", sans-serif;
  font-style: normal;
  font-weight: bold;
  font-size: 20px;
  line-height: 48px;
  color: #ffffff;
  text-align: center;
`;

const Background = styled.img`
  position: absolute;
  width: 100%;
  top: 0px;
  z-index: -1;
`;

下面是 App.tsx 中包含的代碼

import React from 'react';
import logo from './logo.svg';
import './App.css';
import Home from "./components/Home";
import { Route, Link } from 'react-router-dom';
//import { Route, Router, Link } from "react-router-dom";


function App() {
  return (
    <div className="App">
      <header className="App-header">

  {/*      <Home />*/}
        <div>
          <nav>
            <ul>
              <li>
                <Link to={'/'}> Home </Link>
              </li>

              <li>
              </li>
            </ul>
          </nav>

            <Route path={'/'} element={<Home/>} />

        </div>
      </header>
    </div>
  );
}

export default App;
//export default Table;

這是因為您沒有從Home返回任何內容,因為從未調用過Table function。 是一個工作示例。

import React, { useEffect, useState } from "react";
import styled from "styled-components";
import { Route, Router } from "react-router-dom";
//import  styledComponents from "styled-components";

// Could not find a declaration file for module 'styled-components'. '/var/www/html/public_html/react_js/myapp_task/node_modules/styled-components/dist/styled-components.cjs.js' implicitly has an 'any' type.
//   Try `npm i --save-dev @types/styled-components` if it exists or add a new declaration (.d.ts) file containing `declare module 'styled-components';`

import backgroundImage from "./background.png";

const Home = () => {
  const [users, setUsers] = useState<YourUserType[]>([]);
  //const [users, setUsers] = useState("");

  useEffect(() => {
    const url = "https://jsonplaceholder.typicode.com/users";

    const fetchData = async () => {
      try {
        /*         const response = await fetch(url,);
        const json = await response.json();
        console.log(json.slip.users);
        setUsers(json.slip.users); */
        fetch(url)
          .then((response) => response.json())
          .then((data) => {
            console.log(JSON.stringify(data));
            setUsers(data);
          });
      } catch (error) {
        console.log("error", error);
      }
    };

    fetchData();
  }, []);
  //type Users = typeof users
  //type Users = typeof users {
  type YourUserType = {
    id: string;
    name: string;
    username: {
      slug: string;
    };
    email: string;
    address: string;
  };

  // const Table = ({ users }: { users: YourUserType[] }) => {

  return (
    <table>
      <thead>
        <tr>
          <th>Id</th>
          <th>Name</th>
          <th>Username</th>
          <th>Email</th>
          <th>Address</th>
        </tr>
      </thead>
      <tbody>
        {users.length > 0 ? (
          users.map((user, idx) => {
            return (
              <tr key={idx}>
                <td>{user.id}</td>
                <td>{user.name}</td>
                <td>{user.username.slug}</td>
                <td>{user.email}</td>
                <td>{JSON.stringify(user.address)}</td>
              </tr>
            );
          })
        ) : (
          <tr>
            <td>Loading...</td>
          </tr>
        )}
      </tbody>
    </table>
  );
  //  }
};
export default Home;

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM