最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - Passing array of React components to useState returns empty array - Stack Overflow

programmeradmin2浏览0评论

Very simple code here. I'm wondering if this is the expected outcome. I'm upgrading an npm module and it requires I pass these items to useState which was not previously necessary. Unfortunately, I guess this can't be done with useState? Am I right? I'd love to be wrong.


Where props.items contains an array of class-based React components, useState returns an empty array:

const [items, set] = useState(props.items);

Input:

Output:

*Note, images use prop spreading inside of array because I'm out of ideas besides, rework all the things.

Very simple code here. I'm wondering if this is the expected outcome. I'm upgrading an npm module and it requires I pass these items to useState which was not previously necessary. Unfortunately, I guess this can't be done with useState? Am I right? I'd love to be wrong.


Where props.items contains an array of class-based React components, useState returns an empty array:

const [items, set] = useState(props.items);

Input:

Output:

*Note, images use prop spreading inside of array because I'm out of ideas besides, rework all the things.

Share Improve this question asked Feb 6, 2020 at 19:39 SlboxSlbox 13.1k16 gold badges64 silver badges131 bronze badges
Add a comment  | 

2 Answers 2

Reset to default 12

This is not really recommanded you better do it in the useEffect because Props in Initial State is an anti-pattern.

const [items, setItems] = useState([]);


useEffect(() => {
    setItems(props.items);
  },[props.items]);

You should have no issues with using react element array as the input to useState. But, whenever you initialize your state with props coming from parent, you also need to re-update your state once the prop from parent changes. Otherwise it will point to the old state passed down from parent in the first pass. And the way to do that is to do a setItems with useEffect hook

useEffect(() => {
   setItems(props.items)
}, [props.items])

btw this will only check for the reference equality between the old and the new array, if you want to do deep comparison, you should probably be using something like use-deep-compare-effect

发布评论

评论列表(0)

  1. 暂无评论