当存储在反应状态中时,数组变成对象

我正在从我的 api 获取一些数据。在获取数据的回调中,数据是一个数组:


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

        });

}, []); 

在我的功能组件的 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>


肥皂起泡泡
浏览 57回答 1
1回答

慕的地6264312

因为你是双层包装的。React 仅使用单一包装。仅使用一组{}这样的{posts.map( ... )}:<div className="post__container">&nbsp; {posts.map((post, i) => (&nbsp; &nbsp; <MiniPost&nbsp; &nbsp; &nbsp; dp="https://picsum.photos/200"&nbsp; &nbsp; &nbsp; username="blah"&nbsp; &nbsp; &nbsp; time="blah"&nbsp; &nbsp; &nbsp; heading="blah"&nbsp; &nbsp; &nbsp; comments="4"&nbsp; &nbsp; &nbsp; history={history}&nbsp; &nbsp; &nbsp; key={i}&nbsp; &nbsp; />&nbsp; ))}</div>
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

JavaScript