TS2339: 属性 ‘users’ 不存在于类型 ‘{}’ 上

huangapple go评论137阅读模式
英文:

TS2339: Property 'users' does not exist on type '{}'

问题

我正在学习React时从JavaScript(JS)切换到TypeScript(TS),现在我面临着这个问题。

我的上下文(context)的初始状态是空的,无法找到属性。

这里是存储库链接,如果你喜欢的话
https://github.com/lets-c-whats/ts-github-finder/blob/main/src/components/users/UserResults.tsx

上下文文件

const GithubContext = createContext({});

interface GithubContextProps {
  children: React.ReactNode;
}

export const GithubProvider = ({ children }: GithubContextProps) => {
  const [users, setUsers] = useState<User[]>([]);
  const [loading, setLoading] = useState<boolean>(true);

  const fetchUsers = async () => {
    const response = await fetch(`${GITHUB_URL}/users`, {
      headers: {
        Authorization: `token ${GITHUB_TOKEN}`,
      },
    });

    const data = await response.json();

    setUsers(data);
    setLoading(false);
  };

  return (
    <GithubContext.Provider
      value={{
        users,
        loading,
        fetchUsers
      }}
    >
      {children}
    </GithubContext.Provider>
  );
};

export default GithubContext;

我在应用程序中使用提供者包装App,并在Home组件内部包含了UserResults组件

import { GithubProvider } from "./context/github/githubContext";
...
function App() {
  return (
    <GithubProvider>
      ...
      <Route path="/" element={<Home />} />
    </GithubProvider>
  );
}

之后,我在组件内部使用useContext钩子请求值

// 依赖项
import { useEffect, useContext } from "react";
import GithubContext from "../../context/github/githubContext";

function UserResults() {
  const {users, loading, fetchUsers} = useContext(GithubContext)

  useEffect(() => {
    fetchUsers()
  })

  if (!loading) {
    return (
      <div className="grid grid-cols-1 gap-8 xl:grid-cols-4 lg:grid-cols-3 md:grid-cols-2">
        {users.map((user) => {
          return <UserItem key={user.id} userData={user} />
        })}
      </div>
    );
  } else {
    return <Spinner />
  }
}
export default UserResults;

然后应用程序不起作用,会引发以下错误:

TS2339: 属性'users'在类型'{}'上不存在。
     8 |
     9 | function UserResults() {
  > 10 |   const {users, loading, fetchUsers} = useContext(GithubContext)
       |          ^^^^^
    11 |
    12 |   useEffect(() => {
    13 |     fetchUsers()

ERROR in src/components/users/UserResults.tsx:10:17

TS2339: 属性'loading'在类型'{}'上不存在。
     8 |
     9 | function UserResults() {
  > 10 |   const {users, loading, fetchUsers} = useContext(GithubContext)
       |                 ^^^^^^^
    11 |
    12 |   useEffect(() => {
    13 |     fetchUsers()

ERROR in src/components/users/UserResults.tsx:10:26

TS2339: 属性'fetchUsers'在类型'{}'上不存在。
     8 |
     9 | function UserResults() {
  > 10 |   const {users, loading, fetchUsers} = useContext(GithubContext)
       |                          ^^^^^^^^^^
    11 |
    12 |   useEffect(() => {
    13 |     fetchUsers()

ERROR in src/components/users/UserResults.tsx:19:21

TS7006: 参数'user'隐式具有'any'类型。
    17 |     return (
    18 |       <div className="grid grid-cols-1 gap-8 xl:grid-cols-4 lg:grid-cols-3 md:grid-cols-2">
  > 19 |         {users.map((user) => {
       |                     ^^^^
    20 |           return <UserItem key={user.id} userData={user} />
    21 |         })}
    22 |       </div>
英文:

Im switching from JS to TS while learning React. Im facing this problem now.

The initial state for my context is empty and it cannot find the properties.

Here the repo if you prefer
https://github.com/lets-c-whats/ts-github-finder/blob/main/src/components/users/UserResults.tsx

context file

const GithubContext = createContext({});

interface GithubContextProps {
  children: React.ReactNode;
}

export const GithubProvider = ({ children }: GithubContextProps) => {
  const [users, setUsers] = useState<User[]>([]);
  const [loading, setLoading] = useState<boolean>(true);

  const fetchUsers = async () => {
    const response = await fetch(`${GITHUB_URL}/users`, {
      headers: {
        Authorization: `token ${GITHUB_TOKEN}`,
      },
    });

    const data = await response.json();

    setUsers(data);
    setLoading(false);
  };

  return (
    <GithubContext.Provider
      value={{
        users,
        loading,
        fetchUsers
      }}
    >
      {children}
    </GithubContext.Provider>
  );
};

export default GithubContext;

Im wraping the App with the provider and within Home component is the component UserResults

import { GithubProvider } from "./context/github/githubContext";
...
function App() {
  return (
    <GithubProvider>
      ...
      <Route path="/" element={<Home />} />
    </GithubProvider>
  );
}

After that Im requesting the values inside the component using the useContext hook

// DEPENDENCIES
import { useEffect, useContext } from "react";
import GithubContext from "../../context/github/githubContext";



function UserResults() {
  const {users, loading, fetchUsers} = useContext(GithubContext)

  useEffect(() => {
    fetchUsers()
  })

  if (!loading) {
    return (
      <div className="grid grid-cols-1 gap-8 xl:grid-cols-4 lg:grid-cols-3 md:grid-cols-2">
        {users.map((user) => {
          return <UserItem key={user.id} userData={user} />;
        })}
      </div>
    );
  } else {
    return <Spinner />
  }
}
export default UserResults;

after all that the app does not work it throws these errors:

TS2339: Property 'users' does not exist on type '{}'.
     8 |
     9 | function UserResults() {
  > 10 |   const {users, loading, fetchUsers} = useContext(GithubContext)
       |          ^^^^^
    11 |
    12 |   useEffect(() => {
    13 |     fetchUsers()


ERROR in src/components/users/UserResults.tsx:10:17

TS2339: Property 'loading' does not exist on type '{}'.
     8 |
     9 | function UserResults() {
  > 10 |   const {users, loading, fetchUsers} = useContext(GithubContext)
       |                 ^^^^^^^
    11 |
    12 |   useEffect(() => {
    13 |     fetchUsers()


ERROR in src/components/users/UserResults.tsx:10:26

TS2339: Property 'fetchUsers' does not exist on type '{}'.
     8 |
     9 | function UserResults() {
  > 10 |   const {users, loading, fetchUsers} = useContext(GithubContext)
       |                          ^^^^^^^^^^
    11 |
    12 |   useEffect(() => {
    13 |     fetchUsers()


ERROR in src/components/users/UserResults.tsx:19:21

TS7006: Parameter 'user' implicitly has an 'any' type.
    17 |     return (
    18 |       <div className="grid grid-cols-1 gap-8 xl:grid-cols-4 lg:grid-cols-3 md:grid-cols-2">
  > 19 |         {users.map((user) => {
       |                     ^^^^
    20 |           return <UserItem key={user.id} userData={user} />;
    21 |         })}
    22 |       </div>

答案1

得分: 1

你没有为你的上下文定义类型。修复方法如下:

type GithubContextTypes = {
    users: User[];
    loading: boolean;
    fetchUsers: () => void;
}

const GithubContext = createContext({} as GithubContextTypes);
英文:

You are not defining your types for your context. Fix would be like this

type GithubContextTypes = {
    users: User[];
    loading: boolean;
    fetchUsers: () => void;
}

const GithubContext = createContext({} as GithubContextTypes);

huangapple
  • 本文由 发表于 2023年3月7日 04:06:16
  • 转载请务必保留本文链接:https://go.coder-hub.com/75655362.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定