dev*_*_el 5 javascript reactjs next.js
我用来next/router处理页面转换。
When a user clicks on a list of numbers from 1-4 on page a, I save the number they click via localStorage and reorder my list of numbers on page b.
For example, if the default order on page a is
1, 2, 3, 4
Run Code Online (Sandbox Code Playgroud)
And the user clicks 4
next/router send the user to page b with the changed order
4, 1, 2, 3
Run Code Online (Sandbox Code Playgroud)
Below is my page a code
import { useState, useEffect } from 'react'
import { useRouter } from 'next/router'
import { setLocalStorage } from '../../../utils/common'
import styles from './test.module.scss'
export default function NewHome() {
const router = useRouter()
const numbers = [1, 2, 3, 4]
const [order, setOrder] = useState([1, 2, 3, 4])
const handleClick = (e): void => {
let _order = order.filter((num) => num !== Number(e.target.id))
setOrder([Number(e.target.id), ..._order])
router.push('/renewal/test/b')
}
useEffect(() => {
const contact = { order }
setLocalStorage(contact)
}, [order])
return (
<div className={styles.a}>
{numbers.map((number) =>
<p id={String(number)} key={number} onClick={handleClick}>{number}</p>
)}
</div>
)
}
Run Code Online (Sandbox Code Playgroud)
Below is my page b code
import { useState, useEffect } from 'react'
import { getLocalStorage } from '../../../utils/common'
import styles from './test.module.scss'
export default function NewHome() {
const [items, setItems] = useState([])
useEffect(() => {
const _contact = getLocalStorage()
setItems(_contact.order)
}, [])
return (
<div className={styles.b}>
{items.map((number) =>
<p key={number}>{number}</p>
)}
</div>
)
}
Run Code Online (Sandbox Code Playgroud)
Below is my localStorage code
export const setLocalStorage = (contact) => {
const _contact = getLocalStorage()
const updateContact = {
..._contact,
...contact
}
window.localStorage.setItem('contact', JSON.stringify(updateContact))
}
export const getLocalStorage = () => {
const contact = JSON.parse(window.localStorage.getItem('contact'))
return contact
}
Run Code Online (Sandbox Code Playgroud)
My problem is that when the user first clicks on any number on page a, there is a noticeable 1 second delay before the page transition to page b.
If I click the back button to go to page a from b and click on a number again, the delay is gone. But if I reload page a and try again, the 1 second delay returns.
I suspect
router.push('/renewal/test/b')
Run Code Online (Sandbox Code Playgroud)
is causing the delay. But I am not sure if this entirely a nextjs issue, or a react issue, or a localStorage issue.
How can I reduce my 1 second delay when the user first transitions from page a to page b?
| 归档时间: |
|
| 查看次数: |
5023 次 |
| 最近记录: |