简体   繁体   English

React State 不会在第一次点击时更新

[英]React State does not update on first click

I was trying to build a simple data displaying system with two sorting buttons (ascending & descending).我试图用两个排序按钮(升序和降序)构建一个简单的数据显示系统。

The way I did it was fetch & display data from array using map method.我这样做的方式是使用 map 方法从数组中获取和显示数据。 Then in another component file I use useEffect to trigger the sorting.然后在另一个组件文件中,我使用 useEffect 来触发排序。

The problem is the system doesn't rerenders instantly when I first click the button.问题是当我第一次单击按钮时系统不会立即重新渲染。 The system will only rerenders on the second time I click the button (and showing result of first click).系统只会在我第二次单击按钮时重新渲染(并显示第一次单击的结果)。

Fetch data:获取数据:

useEffect(() => {
 fetchData();
},[])

const fetchData = () => {
 SetItems(data.items)
}

Iterate data迭代数据

<div>
    {items.map((item)=>
   <Details key={item.slug} item={item} />)}
</div>

Inside the Details component,在 Details 组件中,

useEffect(() => {
 if(category==='ascending'){
 const sorted = items.sort((a,b) => a.time > b.time ? 1 : -1);
 setItems(sorted);}

 if(category==='descending'){
 const sorted = items.sort((a,b) => a.time < b.time ? 1 : -1);
 setItems(sorted);}

},[category])

assign sorted data to items, useEffect should re-renders every time the category is changed.将排序数据分配给项目,每次更改类别时,useEffect 都应该重新呈现。

<button onClick={()=>setCategory('ascending') />
<button onClick={()=>setCategory('descending') />

When I click on a button, the system will not rerenders, the state will only renders after I click on the second button.当我点击一个按钮时,系统不会重新渲染,只有在我点击第二个按钮后才会渲染状态。 For example:例如:

  1. Click 'Ascending Button' -> Nothing changes.单击“升序按钮”-> 没有任何变化。
  2. Click 'Descending Button' -> Data sorted by Ascending Order.单击“降序按钮”-> 按升序排序的数据。
  3. Click 'Ascending Button' -> Data sorted by Descending Order.单击“升序按钮”-> 按降序排序的数据。

*But the data shows correctly using console.log *但数据使用console.log正确显示

sort() 'returns the reference to the same array', meaning when after sorting and updating your state, it checks and see's its still referencing the same array, and will not rerender. sort() '返回对同一个数组的引用',这意味着在排序和更新你的状态后,它会检查并查看它是否仍然引用同一个数组,并且不会重新渲染。 You need to copy the array when setting its state设置状态时需要复制数组

useEffect(() => {
 if(category==='ascending'){
 const sorted = items.sort((a,b) => a.time > b.time ? 1 : -1);
 setItems([...sorted]);}

 if(category==='descending'){
 const sorted = items.sort((a,b) => a.time < b.time ? 1 : -1);
 setItems([...sorted]);}

},[category])

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

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