Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
220 views
in Technique[技术] by (71.8m points)

reactjs - What's wrong with my custom hook in React?

Hi Stack Overflow Community!

I am learning react and now I am practicing custom hooks. I get the example data from here: https://jsonplaceholder.typicode.com/posts

I've got two components.

App.js

import React from "react";
import useComments from "./hooks/useComments"

const App = () => {

  const Comments = useComments();

  const renderedItems = Comments.map((comment) => {
    return <li key={comment.id}>{comment.title}</li>;
  });

  return (
    <div>
      <h1>Comments</h1>
     <ul>{renderedItems}</ul> 
    </div>
  );
}

export default App;

useComments.js

import {useState, useEffect} from "react";

const useComments = () => {

    const [Comments, setComments] = useState([]);

    useEffect(() => {
        fetch("https://jsonplaceholder.typicode.com/posts", {
            "mode": "cors",
            "credentials": "omit"
        }).then(res => res.json()).then(data => setComments(data))
    }, []);


    return [Comments];
};

export default useComments;

My output looks like this and i don't know why. There are no warnings or errors.

output

question from:https://stackoverflow.com/questions/65643304/whats-wrong-with-my-custom-hook-in-react

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

This line makes Comments be an array:

const [Comments, setComments] = useState([]);

...and then you're wrapping it in an additional array:

return [Comments];

But when you use it, you're treating it as a single dimensional array.

const Comments = useComments();

const renderedItems = Comments.map...

So you'll just need to line those two up. If you want two levels of array-ness (perhaps because you plan to add more to your hook, so that it's returning more things than just Comments), then the component will need to remove one of them. This can be done with destructuring, as in:

const [Comments] = useComments();

Alternatively, if you don't need that complexity, you can change your hook to not add the extra array, and return this:

return Comments;

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...