刷新问题:使用路径名和 url 数组设置 React/Gatsby 中的下一个和上一个链接

Refresh issue: Use pathname & array of urls to set next and previous links in React/Gatsby

我正在使用一组链接进行分页,因为我希望它们按特定顺序排列。这一切都很好,如果我导航到任何我可以通过它们分页的功能页面;但是如果我刷新页面,Next href 默认为 [0] 或 'features/safety-training',而 Prev 最终未定义。我假设这与 useEffect 的工作方式有关,但我不确定如何解决它。

   const [position, setPosition] = useState(null);
   const [next, setNext] = useState(null);
   const [prev, setPrev] = useState(null);

     let theArray =[
        "/features/safetytraining", 
        "/features/certificatetracking", 
        "/features/policies", 
        "/features/standard-operating-procedures", 
        "/features/competencies", 
        "/features/contractor-orientations", 
        "/features/worksite-screening", 
        "/features/inspections", 
        "/features/incident-reporting", 
        "/features/behavior-observations", 
        "/features/bulletins", 
        "/features/suggestions", 
        "/features/polls", 
        "/features/whistleblower"
    ]

    useEffect(() => {

        let pathname = window.location.pathname

        //Check the array for pathname

        let checkPosition = theArray.indexOf(pathname);

       //Set the position to pathname index

        setPosition(checkPosition)

    });

       //Update next/prev when position changes

    useEffect(() => {

        setNext(theArray[position +1])

        setPrev(theArray[position -1])

    }, [position]);  


链接如下:

            <>
            <button 
            style={{marginRight: '15px'}}>
                <Link to={prev}>Prev</Link>
                </button>

            <button>
                <Link to={next}>Next</Link>
                </button>
            </> 

你不需要任何状态或副作用(useEffect):

// Pages don't change and don't depend on props or state,
// so let's define w/ `const` and extract from the
// component to avoid recreating on each render:
const pages = [
  "/features/safetytraining",
  "/features/certificatetracking",
  "/features/policies",
  "/features/standard-operating-procedures",
  "/features/competencies",
  "/features/contractor-orientations",
  "/features/worksite-screening",
  "/features/inspections",
  "/features/incident-reporting",
  "/features/behavior-observations",
  "/features/bulletins",
  "/features/suggestions",
  "/features/polls",
  "/features/whistleblower",
];

const Example = () => {
  // This is extraordinarily cheap to compute and will not
  // change without a re-render occurring, so we don't need
  // for it to be state:
  const position = typeof window === "undefined"
    ? 0
    : pages.indexOf(window.location.pathname);

  // Avoid using an invalid index position
  const prevPath = position <= 0 ? pages[pages.length] : pages[position - 1];
  const nextPath = position >= pages.length - 1 ? pages[0] : pages[position];

  return (
    <div>
      <button style={{ marginRight: "15px" }}>
        <Link to={prevPath}>Prev</Link>
      </button>

      <button>
        <Link to={nextPath}>Next</Link>
      </button>
    </div>
  );
};

您的原始代码产生了一些问题:

  • 每次调用 setter 函数(例如 setPosition),React 都会对组件的重新渲染进行排队
  • 在初始渲染中,positionprevnext 都是 null
  • 进行服务器端渲染时,不会调用 useEffect,因此您的链接会在初始加载时中断
  • 在客户端安装组件后,两个 useEffect 挂钩都会被调用
    1. 第一个钩子会调用 setPosition,提示重新渲染设置了 position 的地方(prevnext 仍然是 null) ;由于没有依赖数组,所以又调用了第一个钩子,又调用了setPosition
    2. 由于 position 更改并调用 setPrevsetNext,将再次调用第二个挂钩,提示再重新渲染两次
    3. 在下一次渲染时,prev 会被设置,但 next 不会
    4. 在下一次渲染中,next 最终将按预期设置