简体   繁体   English

反应 setState() 没有在某些项目上设置 state

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

I'm new to React and have some pretty simple code that is acting strange (I think).我是 React 的新手,并且有一些非常简单的代码表现得很奇怪(我认为)。

The main app fetches a list of blog posts from a server, then passes them through props to a child component which spits the list out.主应用程序从服务器获取博客文章列表,然后通过 props 将它们传递给将列表吐出的子组件。 By default, I'm trying to make the posts only show a preview like a title, and each post will have a state attached to it so I can keep track of which ones are fully shown or previewed.默认情况下,我试图使帖子仅显示标题之类的预览,并且每个帖子都将附加一个 state,以便我可以跟踪哪些帖子已完全显示或预览。

I have the states set up like this:我有这样的状态设置:

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

The list initially is rendered as an empty list so nothing gets returned.该列表最初呈现为空列表,因此不会返回任何内容。 When the data fetch finishes, it re-renders with all the posts.数据获取完成后,它会重新呈现所有帖子。

I use useEffect for this in the child component:我在子组件中为此使用了 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])

Hopefully, I explained clearly what I'm confused about - I can setState using a hard-coded array, but passing in props.posts does not do anything, even though it has content.希望我清楚地解释了我的困惑 - 我可以使用硬编码数组 setState ,但传入 props.posts 不会做任何事情,即使它有内容。

There is nothing wrong about your code, and the reason console.log(posts) spits empty array, it because setPosts(props.posts) is async call and not executed immediately, but tells react it should render again with new value for state.您的代码没有任何问题, console.log(posts)吐出空数组的原因是因为setPosts(props.posts)是异步调用并且不会立即执行,而是告诉 react 它应该使用 state 的新值再次呈现。

Sometimes, like in your hardcoded array case, the code will work "fine", but it not guaranteed, for sure in production when code executed faster有时,就像在硬编码数组的情况下,代码会“正常”工作,但不能保证,当代码执行得更快时,肯定会在生产中

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

Actually, your first issue is about understanding the state changing and the re-rendering on ReactJS.实际上,您的第一个问题是关于了解 state 的变化和 ReactJS 上的重新渲染。 why you do not use the first initial state in the first render just like below:为什么你不在第一个渲染中使用第一个初始 state,如下所示:

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

Also, there is no need to have the first line you can use it exactly on the second line initializing, like this:此外,没有必要让第一行您可以在第二行初始化时完全使用它,如下所示:

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

After all, when you are using a useEffect or other hooks APIs, please add the specific internal state or prop name to dependencies, no put all the props in the array of dependencies, it caused bad costs and make your project slow to run.毕竟,当你使用useEffect或其他 hooks API 时,请在依赖项中添加特定的内部 state 或 prop 名称,不要将所有 props 都放在依赖项数组中,这会造成不好的成本并让你的项目运行缓慢。

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

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