繁体   English   中英

绑定元素“用户”隐式具有“任何”类型

[英]Binding element 'users' implicitly has an 'any' type

Trying to fetch data using api in react and typescript though it's giving me an error.i want to display the data from the json api.i am new to react and typescript. 我正在使用 useEffect function 来调用 api。下面的代码在 src/components/Home.tsx

import React, { useEffect, useState } from "react";
import styled from "styled-components";
//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 App = () => {
  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();
  }, []);

  //return (
      const Table = ({ users }) => {
  return (
    <table>
      <thead>
        <tr>
          <th>Id</th>
          <th>Name</th>
          <th>Region</th>
          <th>Memory</th>
          <th>CPUs</th>
          <th>Disk Size</th>
        </tr>
      </thead>
      <tbody>
        { (users.length > 0) ? users.map( (users, index) => {
           return (
            <tr key={ index }>
              <td>{ users.id }</td>
              <td>{ users.name }</td>
              <td>{ users.username.slug}</td>
              <td>{ users.email}</td>
              <td>{ users.address}</td>
              <td>{ users.street}</td>
              <td>{ users.suite}</td>
            </tr>
          )
         }) : <tr><td colSpan="5">Loading...</td></tr> }
      </tbody>
    </table>
  );
}
export default App;

您需要指定道具的类型

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM