简体   繁体   English

数组在反应中以状态存储时成为对象

[英]Array becoming object when stored in state in react

I am getting some data from my api.我正在从我的 api 获取一些数据。 In the callback from fetching the data, the data is an array:在获取数据的回调中,数据是一个数组:

const classes = useStyles();

const [posts, setPosts] = useState([]);

useEffect(() => {
    fetch('https://forum-temp.herokuapp.com/api/posts')
        .then((res) => res.json())
        .then((res) => {
            console.log(typeof res.data.docs) // Array
            setPosts(res.data.docs);
        });
}, []); 

Inside the return statement of my functional component -在我的功能组件的 return 语句中 -

<div className="post__container">
                    { {posts.map((post, i) => (
                        <MiniPost
                            dp="https://picsum.photos/200"
                            username="blah"
                            time="blah"
                            heading="blah"
                            comments="4"
                            history={history}
                            key={i}
                        />
                    ))} }
    </div>

It's because you're double wrapping.那是因为你是双重包装。 React uses only single wrapping. React 仅使用单包装。 Use only one set of {} like this {posts.map( ... )} :仅使用一组{}像这样{posts.map( ... )}

<div className="post__container">
  {posts.map((post, i) => (
    <MiniPost
      dp="https://picsum.photos/200"
      username="blah"
      time="blah"
      heading="blah"
      comments="4"
      history={history}
      key={i}
    />
  ))}
</div>

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

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