【问题标题】:Need useEffect hook invoke when URL changesURL 更改时需要调用 useEffect 挂钩
【发布时间】:2020-12-11 17:56:42
【问题描述】:

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

【问题讨论】:

  • 将 currentUrl 传递给 useEffect 依赖数组 => [currentUrl]
  • currentUrl 添加到useEffect 的dep 数组中。现在它没有接收到变化,因为你没有向它提供你想要观察的变量。

标签: reactjs react-hooks


【解决方案1】:

要使 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]);

【讨论】:

    猜你喜欢
    • 2022-01-26
    • 1970-01-01
    • 2020-02-12
    • 2019-07-31
    • 2020-05-17
    • 1970-01-01
    • 2021-02-14
    • 2022-01-17
    • 2021-07-28
    相关资源
    最近更新 更多