简体   繁体   English

使用数组默认值反应 useState()

[英]React useState() with array default value

I am trying to use React useState to store an array of objects but I'm having a strange problem.我正在尝试使用 React useState 来存储对象数组,但我遇到了一个奇怪的问题。 The state will not take on the value I give it.国家不会承担我赋予它的价值。 I have tried all of the following:我已经尝试了以下所有方法:

const [items,setItems] = useState(props.items)

const [items,setItems] = useState([...props.items])

const clone = [...props.items]
const [items,setItems] = useState(clone)

but the value of items after each solution is an empty array.但是每个解决方案之后的项目值是一个空数组。 Even when props.items is not an empty array.即使props.items不是空数组。

It works when I do for example例如,当我这样做时它有效

const demo = [{hello:'world'}]
const [items,setItems]=useState(demo)

Does anyone know the problem?有谁知道问题所在?

EDIT:编辑:

Concrete example:具体例子:

This is the relevant part of the calling (parent) react functional element这是调用(父)反应功能元素的相关部分

const overviews = props.overviews.map((obj, index) => ({ ...obj, onClick: myOnClick}));
return <DragSort items={overviews}/>

then然后

const Dragsort = (props) => {
    const [ items, setItems ] = useState(props.items);
    console.log('dragsort 1:', props.items);
    console.log('dragsort 2:', items);
    console.log('dragsort 3:', props.items instanceof Array);
    console.log('dragsort 4:', items instanceof Array);
...

gives

在此处输入图片说明

Try to ensure that you are checking the result for the first time that the component is rendering.尝试确保您正在检查组件渲染的第一次结果。 What may be happening is that you are looking at the result for the 2nd, or nth render, and at this point the state has already been set to a incorrect (in this case an empty array) value.可能发生的情况是您正在查看第 2 次或第 n 次渲染的结果,此时状态已设置为不正确(在本例中为空数组)值。

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

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