reactjs - 当 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>
</>
);
}
解决方案
异步函数应该在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>
</>
);
}
推荐阅读
- kubernetes - 网络策略是否应用于服务或端点?
- java - 如何在 Swing 中使用 GridLayout?
- recaptcha - 与 recaptcha-v2 复选框相比,谷歌 invisible-recaptcha 是否安全?
- python - 嵌套字典与非嵌套字典的性能如何?(Python)
- machine-learning - 我想使用变量 A 的描述性文本并将它们与变量 B 的描述性文本相关联来预测 B。我该怎么做?
- java - 为什么将图像文件从 python 客户端传输到 java 服务器后无法传输字符串?
- python - 使用 Python 访问共享的 Outlook 子文件夹
- arrays - 如何从 JSON 数组中提取值?
- godot - 如何在 godot 3.1 中对 IK 应用约束
- twitter-bootstrap - 在 Bootstrap 4 中删除/取消设置默认 $colors (map-remove)