繁体   English   中英

React.Js 和 Typescript 如何从 JSON 中读取数据?

[英]React.Js and Typescript how to read data from JSON?

每个人。

我正在将 MongoDB 与 mongoose 和 React.Js 一起使用。 我有一个页面,用户可以在其中显示帖子。

我正在将获取请求发送到后端,我在后端获取此 json 数据作为响应。

 {
        "post": {
            "_id": "62cd5b5ef2a39582f96ad514",
            "title": "asdadsad",
            "description": "sdasdasdasda",
            "imageURL": "image 1",
            "creator_id": "62cd5b1bf2a39582f96ad500",
            "createdAt": "2022-07-12T11:30:38.255Z",
            "updatedAt": "2022-07-12T11:30:38.255Z",
            "__v": 0,
            "id": "62cd5b5ef2a39582f96ad514"
        }
    }

在前端,我使用 Fetch API 来获取这些数据,我想做的是我希望能够从 JSON 响应中读取每个键和值,因为我想使用这些数据来显示标题、内容ETC...

  const { isLoading, error, sendRequest, clearError } = useHttpRequest();
  const [getPost, setPost] = useState([]);
  const userID = useParams().id;

  useEffect(() => {
    const fetchPosts = async () => {
      try {

        const url: string = `http://localhost:8000/api/posts/${userID}`;
        const responseData = await sendRequest(url);

       console.log(responseData);
       setPost(responseData);

      } catch (err) { }}

      fetchPosts();
  }, [sendRequest]);

现在我尝试使用 getPost.map(.......),但是当我执行 setPost(responseData.post) 时,我得到了一个错误,说 getPost.map 不是函数事件,我得到了同样的错误。 那么如何访问 JSON 响应中的不同数据呢?

如果这有帮助,那就是我的 sendRequest 函数。 这是我的 sendRequest 位于完全不同的文件中

const useHttpRequest = () => {

    const [isLoading, setIsLoading] = useState(false);
    const [error, setError] = useState<string | null>(null);
    const activeHttpRequests: any = useRef([]);


    const sendRequest = useCallback( async (url: string, method: string = 'GET', body: any = null, headers: {} = {}) => {

        setIsLoading(true);
        const httpAbort = new AbortController();
        activeHttpRequests.current.push(httpAbort);

        try {
            const response = await fetch(url, {
                method: method,
                headers: headers,
                body: body,
                signal: httpAbort.signal //FIX FOR CROSS REQUEST SENDING
              });
  
            const responseData = await response.json();
            
            activeHttpRequests.current = activeHttpRequests.current.filter((requests: any) => requests !== httpAbort);
            if (!response.ok){
                throw new Error("Error fetch failed !");
            }

            setIsLoading(false);
            return responseData;
        } catch (err: any) {
            console.log(err.message)
            setError(err.message);
            setIsLoading(false);
            throw err;
        };
        
    }, [])

    const clearError = () => {
        setError(null);
    }

    useEffect(() => {
        return () => {
            activeHttpRequests.current.forEach((abortRequest: any) => abortRequest.abort()) //ABORT CURRENT REQUEST 
        };
    }, []);

    return { isLoading, error, sendRequest, clearError }
}

export default useHttpRequest

map函数仅存在于数组上,但您提供的数据是一个对象。 您可以使用下标符号访问它或遍历对象的键。

const data = {
    "post": {
        "_id": "62cd5b5ef2a39582f96ad514",
        "title": "asdadsad",
        "description": "sdasdasdasda",
        "imageURL": "image 1",
        "creator_id": "62cd5b1bf2a39582f96ad500",
        "createdAt": "2022-07-12T11:30:38.255Z",
        "updatedAt": "2022-07-12T11:30:38.255Z",
        "__v": 0,
        "id": "62cd5b5ef2a39582f96ad514"
    }
}

// access a single field
console.log(data.post.title) // asdadsad

// iterate over all fields in "post"
Object.keys(data.post).forEach((key, value) => console.log(`${key}: ${data.post[key]}`))

您的返回对象看起来像这样:

export interface Posts {
    post: Post[];
}

export interface Post {
    _id:         string;
    title:       string;
    description: string;
    imageURL:    string;
    creator_id:  string;
    createdAt:   Date;
    updatedAt:   Date;
    __v:         number;
    id:          string;
}

为了简化您的工作并确保您获得正确的数据,您应该考虑在下面执行此操作:

  const { isLoading, error, sendRequest, clearError } = useHttpRequest();
  const [getPost, setPost] = useState<Posts>([]);
  const userID = useParams().id;

  const fetchPosts = async () => {
    try {

      const url: string = `http://localhost:8000/api/posts/${userID}`;
      const responseData = await sendRequest(url);

     console.log(responseData);
     setPost(responseData);

    } catch (err) { }}


  useEffect(() => {
      fetchPosts();
  }, [sendRequest]);

  return (
    <div>
        <h1>get Data</h1>
        {getPost.post.map((value,index) => (
            <li key={`${index}-${value}`}>{value}</li>
        ))}
    </div>
)

暂无
暂无

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

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