首页 > 解决方案 > URL 更改时需要调用 useEffect 挂钩

问题描述

我试图让这个组件根据其当前的 url 加载数据,无论是 /global 还是 /my-posts。useEffect() 从组件的第一次加载中获取数据,但是当我更改为另一个 url 时,我希望 useEffect 再次检查 url 并加载正确的数据,但我却被第一次加载的数据卡住了。每次单击不同的 url(如 /global 和 /my-posts url)时,如何让 useEffect 调用。

export default function Dashboard() {
  const [allRecipes, setAllRecipes] = useState([]);
  const [myRecipes, setMyRecipes] = useState([]);
  const currentUrl = window.location.pathname;

  useEffect(() => {
    if (currentUrl === '/dashboard/global') {
      console.log('hello');
      trackPromise(
        RecipeService.getAllRecipes()
          .then((data) => {
            setAllRecipes(data);
          }),
      );
    } else if (currentUrl === '/dashboard/my-posts') {
      console.log('hi');
      trackPromise(
        RecipeService.getRecipes()
          .then((data) => {
            setMyRecipes(data);
          }),
      );
    }
  }, []);
  console.log(window.location.pathname);
  return (
    <>
      <div className="dashboard">
        <DashboardHeader />
        <div className="created-posts">
          {allRecipes.length !== 0
            ? allRecipes.map((recipe) => <Post recipe={recipe} key={uuidv1()} />)
            : null}
          {myRecipes.length !== 0
            ? myRecipes.recipes.map((recipe) => <Post recipe={recipe} key={uuidv1()} />)
            : null}
          {currentUrl === '/dashboard/create' ? <CreateForm /> : null}
          <LoadingIndicator />
        </div>
      </div>
    </>
  );
}

标签: reactjsreact-hooks

解决方案


React.useEffect在每次currentUrl更改时运行,您必须将其添加到useEffect依赖项数组中。

// first we need to control the state of window.location.pathname by react not the browser
// and make react state be the only source of truth.
const pathname = window.location.pathname

// manage currentUrl in state.
const [currentUrl, setCurrentUrl] = React.useState(pathname)
React.useEffect(() => {
   setCurrentUrl(pathname)
}, [pathname])

// now you would add the contolled `currentUrl` state to its useEffect deps.
useEffect(() => {
  if (currentUrl === '/dashboard/global') {
    // ..........
  } else if (currentUrl === '/dashboard/my-posts') {
    // ..........
  }
}, [currentUrl]);

推荐阅读