url 中 id 更改时如何重新渲染功能组件

How to rerender function component when id changed in url

我有一个 React 组件,它从 IndexedDB 获取一些数据,这是一个异步任务,它使用 useParams 钩子传入的 url 中的 id,假设 id = 1。 当我单击示例中的 link 时,id 更改为 2 但此时没有任何反应,组件不会重新呈现。

我需要做什么才能让它发挥作用?我只是不明白为什么它现在不起作用。 谁能赐教一下?

import React, {useState} from 'react';
import { Link, useParams } from "react-router-dom";
import { useAsync } from 'react-async';

export default function (props) {
  let {id} = useParams();
  const {data, error, isLoading} = useAsync({ promiseFn: loadData, id: parseInt(id)});
  if (isLoading) return "Loading...";
  if (error) return `Something went wrong: ${error.message}`;
  if (data)
   return (
    <>
      <h1>{data.name}</h1>
      <Link to={'/2'}>other id</Link>
    </>
   );
}

异步函数应该在 useEffect 钩子中调用。 useEffect 将在 id 更改时始终被调用。

import React, { useState } from "react";
import { Link, useParams } from "react-router-dom";
import { useAsync } from "react-async";

export default function(props) {
  let { id } = useParams();

  const [error, setError] = useState(null);
  const [isLoading, setIsLoading] = useState(false);
  const [data, setData] = useState(null);

  useEffect(() => {
    const { data, error, isLoading } = useAsync({
      promiseFn: loadData,
      id: parseInt(id)
    });
    setIsLoading(isLoading);
    setError(error);
    setData(data)
  }, [id]);

  if (isLoading) return "Loading...";
  if (error) return `Something went wrong: ${error.message}`;
  if (data)
    return (
      <>
        <h1>{data.name}</h1>
        <Link to={"/2"}>other id</Link>
      </>
    );
}

当使用来自 react-async 库的 useAsync 挂钩时,您可以使用 watch 或 watchFn 选项来监视变化。因此更改以下行:

const {data, error, isLoading} = useAsync({ promiseFn: loadData, id: parseInt(id)});

至:

const {data, error, isLoading} = useAsync({ promiseFn: loadData, id: parseInt(id), watch: id});

成功了。