簡體   English   中英

反應 setState() 沒有在某些項目上設置 state

[英]React setState() not setting state on certain items

我是 React 的新手,並且有一些非常簡單的代碼表現得很奇怪(我認為)。

主應用程序從服務器獲取博客文章列表,然后通過 props 將它們傳遞給將列表吐出的子組件。 默認情況下,我試圖使帖子僅顯示標題之類的預覽,並且每個帖子都將附加一個 state,以便我可以跟蹤哪些帖子已完全顯示或預覽。

我有這樣的狀態設置:

const [posts, setPosts] = useState([])
const [postFullView, setPostFullView] = useState([])

該列表最初呈現為空列表,因此不會返回任何內容。 數據獲取完成后,它會重新呈現所有帖子。

我在子組件中為此使用了 useEffect:

    useEffect(() => {
        console.log('render')         //Just to verify this got called
        setPosts(props.posts)         //Logs empty array 3 lines down,
        //setPosts([4,5,6])           //Works fine, gets logged as [4,5,6]
        console.log(props.posts)      //Logs an array of 32 objects - so props is clearly not empty
        console.log(posts)            //Logs empty array as if setPosts did nothing, but logs [4,5,6] if I comment out setPosts(props.post) and use setPosts([4,5,6])

        setPostFullView(posts.map(post => {return {id: post.id, view: false}}))
        console.log(postFullView)     //Will be empty since posts is empty
    }, [props])

希望我清楚地解釋了我的困惑 - 我可以使用硬編碼數組 setState ,但傳入 props.posts 不會做任何事情,即使它有內容。

您的代碼沒有任何問題, console.log(posts)吐出空數組的原因是因為setPosts(props.posts)是異步調用並且不會立即執行,而是告訴 react 它應該使用 state 的新值再次呈現。

有時,就像在硬編碼數組的情況下,代碼會“正常”工作,但不能保證,當代碼執行得更快時,肯定會在生產中

yea its nothing wrong because the setState api is async did not show the changes in log but code is work properly and also if you need to check your state you can use React developer Tools extension for browser too see the state status https://chrome .google.com/webstore/detail/react-developer-tools/fmkadmapgofadopljbjfkapdkoienihi?hl=en

實際上,您的第一個問題是關於了解 state 的變化和 ReactJS 上的重新渲染。 為什么你不在第一個渲染中使用第一個初始 state,如下所示:

const YourComponent = ({ posts: initialPosts }) => {
  const [posts, setPosts] = useState(initialPosts);

此外,沒有必要讓第一行您可以在第二行初始化時完全使用它,如下所示:

const YourComponent = ({ posts: initialPosts }) => {
  const [postFullView, setPostFullView] = useState(
    ({ id }) => ({ id, view: false }) // es6 arrow function with using restructuring assignment and returning the object
  );

畢竟,當你使用useEffect或其他 hooks API 時,請在依賴項中添加特定的內部 state 或 prop 名稱,不要將所有 props 都放在依賴項數組中,這會造成不好的成本並讓你的項目運行緩慢。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM