【问题标题】:The sort method does nothing, and the state remains the samesort 方法什么都不做,状态保持不变
【发布时间】:2022-08-05 16:44:42
【问题描述】:

我想按 id 对 desc 中的对象数组进行排序。
控制台没有错误。
调用 sort 方法后,状态 allPosts 没有任何变化

import { useState } from \"react\";
import Button from \'react-bootstrap/Button\'

export const Home = () => {

    const [allPosts, setAllPosts] = useState([ // here array of objects])

    const sort = () => {
        setAllPosts(allPosts.sort((a, b) => b.id - a.id))
    }
    return (
        <>
            <div>
                <Button onClick={sort}>Sort</Button>
            </div>
        </>
    )
}

export default Home
  • 数组排序是到位,这意味着 React 不知道数组已更改。

标签: javascript reactjs


【解决方案1】:

Array.prototype.sort 不会创建新的数组引用,这与 react 不兼容

尝试这个:

setAllPosts([...allPosts].sort((a, b) => b.id - a.id))

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2010-11-13
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-05-07
    • 2015-01-13
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多