简体   繁体   中英

after updated array list not index instantly -react.js

i need a filter with time "old to new" and "new to old"

here is my code template:

  const timeNewToOld = () => {
  const [paginationUsers,setPaginationUsers] = useState([])
    const newToOld = users.sort((a, b) => {
      return b.Time.localeCompare(a.Time)
    })
    setPaginationUsers(newToOld)
  }

  const timeOldToNew = () => {
    const oldToNew = users.sort((a, b) => {
      return a.Time.localeCompare(b.Time)
    })
    setPaginationUsers(oldToNew)
  }

this functions working but, not responding instantly on web browser. i hope i can explain with these images:

i click on the "newtoold" function and nothing changes: 在此处输入图像描述

i move to the next page and i'm back to the 1st page:

在此处输入图像描述

everything is fine. only the first time I click on the function, it doesn't get instant updates, when I change the page, the index returns to normal.

paginationUsers created here:

  useEffect(() => {
    const getAllData = async () => {
      onSnapshot(_dbRef, (snapshot) => {
        const data = snapshot.docs.map((doc) => {
          return {
            id: doc.id,
            ...doc.data(),
          }
        })
        setUsers(data)
        setUserPageCount(Math.ceil(data.length / 20))
      })
    }
    getAllData()
  }, [])

  useEffect(() => {
    displayUsers(users, setPaginationUsers, userCurrentPage)
  }, [users, setPaginationUsers, userCurrentPage])

i hope i could explain, happy coding..

Array.prototype.sort doesn't create a new array, so react can't know that it changed. Creating a new array should help.

  const timeOldToNew = () => {
    const oldToNew = [...users].sort((a, b) => {
      return a.Time.localeCompare(b.Time)
    })
    setPaginationUsers(oldToNew)
  }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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