首页 > 解决方案 > 当 url 中的 id 更改时如何重新渲染功能组件

问题描述

我有一个 React 组件,它从 IndexedDB 获取一些数据,这是一个异步任务,它使用 useParams 挂钩传入的 url 中的 id,假设 id = 1。当我单击示例中的链接时,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>
    </>
   );
}

标签: reactjsindexeddbreact-router-v5react-async

解决方案


异步函数应该在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>
      </>
    );
}

推荐阅读