如何初始化React中的状态



我创建了一个数字递增的简单状态。当URL的参数改变时,我想初始化State,但是当我尝试这样做时,Render首先运行,而State没有初始化。我检查了console.log,发现即使我在useEffect中执行setState,值也没有改变。请告诉我如何在gastby中初始化状态。

例子
https://example.com?name=john => https://example.com?name=kid
import { useLocation } from "@reach/router";
import React, { useEffect, useState } from "react";

const AreaInfoPannel = ({ className, documentList }) => {
  const location = useLocation();
  const [page, setPage] = useState(1);
  useEffect(() => {
    setPage(1);
  }, [location.href]);
  const contentsLength = documentList.length;
  const increment = () => {
    contentsLength <= page ? setPage(1) : setPage(page + 1);
  };
  const decrement = () => {
    page <= 1 ? setPage(contentsLength) : setPage(page - 1);
  };
  return (
    <div className={className}>
      <button on_click={decrement}>down</button>
      <button on_click={increment}>up</button>
      <div>{page}</div>
    </div>
  );
};
export default AreaInfoPannel;

useLocation"获取URL信息,使用效果;检测URL更改,并使用setState"初始化值

 const [page, setPage] = useState(1); // this is initializing the state
 useEffect(() => {
    setPage(1);// this is updating the state
  }, [location.href]);

所以每次你访问呈现这个组件的url时状态都是initialized不是

最新更新