Tìm kiếm trang web

reactjs - Thuộc tính 'x' không tồn tại trên kiểu 'unknown'


Tôi không hoàn toàn hiểu điều này. Tôi đã tìm kiếm kỹ trên StackOverflow và GitHub, và một trong những giải pháp tôi thử là thêm một generic nhưng tôi nhận được lỗi Expected 0 type arguments, but got 1. dưới useLocation<LocationState>. Dưới đây là mã của tôi. Vấn đề tôi gặp phải là thiết lập kiểu cho {searchvalue} nhưng nó là một kiểu không xác định. Mọi sự giúp đỡ sẽ được đánh giá cao.

import React from "react";
import { useLocation } from "react-router-dom";

interface SearchResultsProps {}

interface LocationState {
    serachValue: string
}

export const SearchResults: React.FC<SearchResultsProps> = ({}) => {

    const location = useLocation<LocationState>();

     const {searchValue} = location.state
    

  return <div>Results Page</div>;

Câu trả lời #1

Đây là liên kết đến tài liệu cho hook useLocation từ react-router-dom: https://reactrouter.com/docs/en/v6/api#uselocation

Nó định nghĩa chữ ký hàm như sau:

declare function useLocation(): Location;

interface Location extends Path {
  state: unknown;
  key: Key;
}

Bạn có thể thấy rằng location.state có kiểu unknown, vì vậy nếu bạn đã đẩy dữ liệu vào trạng thái lịch sử và muốn truy cập nó một cách an toàn về kiểu, bạn có thể khẳng định kiểu dữ liệu mà bạn đã đẩy vào trạng thái như sau:

const location = useLocation();
const {serachValue} = location.state as LocationState;

Đây là một ví dụ hoàn chỉnh:

Sân chơi TS

import {default as React, type ReactElement} from 'react';
import {useLocation} from 'react-router-dom';

type EmptyObject = Record<never, never>;
type LocationState = { serachValue: string; };

function SearchResults (props: EmptyObject): ReactElement {
  const location = useLocation();
  const {serachValue} = location.state as LocationState;
//       ^^^^^^^^^^^
// is now type 'string'
  return (<div>Results Page</div>);
}

Câu trả lời #2

useLocation không được kiểu hóa tổng quát.

export function useLocation(): Location {
  invariant(
    useInRouterContext(),
    // TODO: This error is probably because they somehow have 2 versions of the
    // router loaded. We can help them understand how to avoid that.
    `useLocation() may be used only in the context of a <Router> component.`
  );

  return React.useContext(LocationContext).location;
}

Xóa <LocationState> và gõ giá trị trả về.

Ví dụ :

const { state }: { state: LocationState } = useLocation();

Bài viết liên quan