React - 使用状态对 child 组件数组进行排序
React - sort array of child components with state
目前我正在做一个 React 项目,但在对有状态 child 组件数组进行排序时,我看到了一些意外行为。
如果我有一个 parent 组件
export function Parent(){
const [children, setChildren] = useState([
{name:'Orange',value:2},
{name:'Apple',value:1},
{name:'Melon',value:3}
])
var count = 0
function handleSort() {
var newChildren=[...children]
newChildren.sort((a,b)=>{return a.value-b.value})
setChildren(newChildren)
}
return (
<div>
<button onClick={handleSort}>Sort</button>
{children.map((child) => {
count++
return(<ChildComp key={count} details={child}/>)
})}
</div>
)
}
还有一个child组件
function ChildComp(props){
const[intCount,setIntCount] = useState(0)
function handleCount(){
setIntCount(intCount+1)
}
return (
<div>
<p>{props.details.name}</p>
<button onClick={handleCount}>{intCount}</button>
</div>
)
}
当页面第一次呈现时一切看起来都很棒,三个 div 呈现一个按钮,显示它被点击的次数和在数组中声明的道具名称。我注意到,当我排序时,它会对传递给 child 组件的 props 进行排序,然后重新渲染,但是 child 组件的 intCount 状态与原始位置保持关联并且未排序。有什么方法可以通过排序使状态与数组元素保持耦合,同时仍将状态数据保持在 child 级别,或者是实现此目的将状态提升到 parent 的唯一方法组件并将回调或分派传递给 child 以更新它?
count
不是未排序。它刚刚在您排序时更新。
Keys help React identify which items have changed, are added, or are
removed. Keys should be given to the elements inside the array to give
the elements a stable identity
每次排序时,key
保持不变,因为您使用 count
。
尝试将 value
用作 key
export function Parent(){
// ....
return (
<div>
<button onClick={handleSort}>Sort</button>
{children.map(child => {
return <ChildComp key={child.value} details={child}/> // key is important
})}
</div>
)
}
目前我正在做一个 React 项目,但在对有状态 child 组件数组进行排序时,我看到了一些意外行为。
如果我有一个 parent 组件
export function Parent(){
const [children, setChildren] = useState([
{name:'Orange',value:2},
{name:'Apple',value:1},
{name:'Melon',value:3}
])
var count = 0
function handleSort() {
var newChildren=[...children]
newChildren.sort((a,b)=>{return a.value-b.value})
setChildren(newChildren)
}
return (
<div>
<button onClick={handleSort}>Sort</button>
{children.map((child) => {
count++
return(<ChildComp key={count} details={child}/>)
})}
</div>
)
}
还有一个child组件
function ChildComp(props){
const[intCount,setIntCount] = useState(0)
function handleCount(){
setIntCount(intCount+1)
}
return (
<div>
<p>{props.details.name}</p>
<button onClick={handleCount}>{intCount}</button>
</div>
)
}
当页面第一次呈现时一切看起来都很棒,三个 div 呈现一个按钮,显示它被点击的次数和在数组中声明的道具名称。我注意到,当我排序时,它会对传递给 child 组件的 props 进行排序,然后重新渲染,但是 child 组件的 intCount 状态与原始位置保持关联并且未排序。有什么方法可以通过排序使状态与数组元素保持耦合,同时仍将状态数据保持在 child 级别,或者是实现此目的将状态提升到 parent 的唯一方法组件并将回调或分派传递给 child 以更新它?
count
不是未排序。它刚刚在您排序时更新。
Keys help React identify which items have changed, are added, or are removed. Keys should be given to the elements inside the array to give the elements a stable identity
每次排序时,key
保持不变,因为您使用 count
。
尝试将 value
用作 key
export function Parent(){
// ....
return (
<div>
<button onClick={handleSort}>Sort</button>
{children.map(child => {
return <ChildComp key={child.value} details={child}/> // key is important
})}
</div>
)
}