admin管理员组文章数量:1290984
I have a list and need to reorder list it on clicking any item on the list. Array of string are used for binding. The function that used for reordering is returning the correct value. But the UI is not updating.
import React from 'react';
import ReactDOM from 'react-dom';
function swapElement(array, from, to) {
array.splice(to, 0, array.splice(from, 1)[0])
return array;
}
const List = props => {
let [list, setList] = React.useState(props.item)
const handleClick = index => {
const items = swapElement(list, index, 0);
console.log('UPDATED ARRAYS--------->', items)
setList(items);
}
return <ul> {
list.map((item, i) =>
<li style={{ margin: '25px' }}
onClick={() => handleClick(i)}
key={i}
>
{item}
</li>)
} </ul>
}
ReactDOM.render(
<List item={['A', 'B', 'C', 'D', 'E']} />,
document.getElementById('root')
);
I have a list and need to reorder list it on clicking any item on the list. Array of string are used for binding. The function that used for reordering is returning the correct value. But the UI is not updating.
import React from 'react';
import ReactDOM from 'react-dom';
function swapElement(array, from, to) {
array.splice(to, 0, array.splice(from, 1)[0])
return array;
}
const List = props => {
let [list, setList] = React.useState(props.item)
const handleClick = index => {
const items = swapElement(list, index, 0);
console.log('UPDATED ARRAYS--------->', items)
setList(items);
}
return <ul> {
list.map((item, i) =>
<li style={{ margin: '25px' }}
onClick={() => handleClick(i)}
key={i}
>
{item}
</li>)
} </ul>
}
ReactDOM.render(
<List item={['A', 'B', 'C', 'D', 'E']} />,
document.getElementById('root')
);
Share
Improve this question
edited Aug 8, 2020 at 9:51
Siva Kondapi Venkata
11k2 gold badges19 silver badges31 bronze badges
asked Aug 8, 2020 at 4:29
J. RayhanJ. Rayhan
1112 silver badges4 bronze badges
1 Answer
Reset to default 11The UI isn't freezing, you are mutating your state object and never returning a new array object reference, so react isn't re-rendering the UI.
Shallow copy the array, then mutate new array and return.
function swapElement(array, from, to) {
const newArray = [...array];
newArray.splice(to, 0, newArray.splice(from, 1)[0])
return newArray;
}
Fun fact: You can use array destructuring to swap two elements of an array. This avoids all the array element shifting that occurs with the splicing.
function swapElement(array, from, to) {
const arr = [...array];
[arr[from], arr[to]] = [arr[to], arr[from]];
return arr;
}
本文标签: javascriptReact UI not updating on state changeStack Overflow
版权声明:本文标题:javascript - React UI not updating on state change - Stack Overflow 内容由网友自发贡献,该文观点仅代表作者本人, 转载请联系作者并注明出处:http://www.betaflare.com/web/1741523345a2383321.html, 本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,一经查实,本站将立刻删除。
发表评论