简体   繁体   English

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

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

everyone.每个人。

I am using MongoDB with mongoose and React.Js.我正在将 MongoDB 与 mongoose 和 React.Js 一起使用。 I have a page where the user can display a post.我有一个页面,用户可以在其中显示帖子。

I am sending fetch request to the backend where I am getting this json data as response.我正在将获取请求发送到后端,我在后端获取此 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"
        }
    }

And on the frontend I am using Fetch API, to get this data, what I am trying to do is I want to be able to read every single key and value from the JSON response as I want to use this data to display title, content etc...在前端,我使用 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]);

Now I had tried using the getPost.map(.......), however I got error that said getPost.map is not a function event when I did setPost(responseData.post) I got the same error.现在我尝试使用 getPost.map(.......),但是当我执行 setPost(responseData.post) 时,我得到了一个错误,说 getPost.map 不是函数事件,我得到了同样的错误。 So how can I access different data in the JSON response ?那么如何访问 JSON 响应中的不同数据呢?

In case this helps here is my sendRequest function.如果这有帮助,那就是我的 sendRequest 函数。 and this is my sendRequest that is located in totaly different file这是我的 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

The map function is only present on arrays, but the data you gave is an Object. map函数仅存在于数组上,但您提供的数据是一个对象。 You can access it using subscript notation or iterate over the keys of the object.您可以使用下标符号访问它或遍历对象的键。

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]}`))

Your return Object would look something like this:您的返回对象看起来像这样:

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;
}

To simplify your work and make sure you get the correct data back, you should consider doing this below:为了简化您的工作并确保您获得正确的数据,您应该考虑在下面执行此操作:

  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