admin管理员组文章数量:1200420
I have a simple array in below and I just change index of elements in array by a handler:
const [items, setItems] = useState([
{ id: 5, val: "Italy" },
{ id: 2, val: "Germany" },
{ id: 3, val: "Brazil" },
{ id: 4, val: "Canada" }
]);
My Handler:
const handlePosition = (old_index, new_index) => {
if (new_index >= items.length) {
var k = new_index - items.length + 1;
while (k--) {
items.push(undefined);
}
}
items.splice(new_index, 0, items.splice(old_index, 1)[0]);
setItems(items);
console.log(items);
};
I try to render the items
array as follows:
<ul>
{items.map((item, index) => (
<li key={item.id}>
{item.val}
<button onClick={() => handlePosition(index, index + 1)}>DOWN</button>
<button onClick={() => handlePosition(index, index - 1)}>UP</button>
</li>
))}
</ul>
Now, My array changed properly and updates the state but not re-render.
Here is a demo of my project in CodeSandBox: Link
I have a simple array in below and I just change index of elements in array by a handler:
const [items, setItems] = useState([
{ id: 5, val: "Italy" },
{ id: 2, val: "Germany" },
{ id: 3, val: "Brazil" },
{ id: 4, val: "Canada" }
]);
My Handler:
const handlePosition = (old_index, new_index) => {
if (new_index >= items.length) {
var k = new_index - items.length + 1;
while (k--) {
items.push(undefined);
}
}
items.splice(new_index, 0, items.splice(old_index, 1)[0]);
setItems(items);
console.log(items);
};
I try to render the items
array as follows:
<ul>
{items.map((item, index) => (
<li key={item.id}>
{item.val}
<button onClick={() => handlePosition(index, index + 1)}>DOWN</button>
<button onClick={() => handlePosition(index, index - 1)}>UP</button>
</li>
))}
</ul>
Now, My array changed properly and updates the state but not re-render.
Here is a demo of my project in CodeSandBox: Link
Share Improve this question edited Feb 16, 2023 at 7:52 Amir asked May 19, 2020 at 16:59 AmirAmir 1,3483 gold badges15 silver badges29 bronze badges1 Answer
Reset to default 26It's because the instance of the items
array is not changing.
Try this:
setItems([...items]);
That copies the array to a new identical array. React will see that it's different and will re-render.
本文标签: javascriptReact does not rerender updated array stateStack Overflow
版权声明:本文标题:javascript - React does not re-render updated array state - Stack Overflow 内容由网友自发贡献,该文观点仅代表作者本人, 转载请联系作者并注明出处:http://www.betaflare.com/web/1738585993a2101433.html, 本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,一经查实,本站将立刻删除。
发表评论