Reactjs 钩子不会重新启动部件
我正在使用React with React Router Dom,我不知道为什么我的子组件功能组件在URL更改时不重新呈现。我不知道为什么,当我第一次访问动态页面时,console.logurl会被触发3次 我的孩子部分: 从React导入React; 从./hooks导入{useFetch}; 功能页面道具{ 常量url=https://jsonplaceholder.typicode.com/posts +props.match.url; console.logurl; const[data,loading]=useFetchurl; 回来 {加载? 加载。。。 : {data.title} {data.body} } ; } 导出默认页面;Reactjs 钩子不会重新启动部件,reactjs,components,render,react-hooks,Reactjs,Components,Render,React Hooks,我正在使用React with React Router Dom,我不知道为什么我的子组件功能组件在URL更改时不重新呈现。我不知道为什么,当我第一次访问动态页面时,console.logurl会被触发3次 我的孩子部分: 从React导入React; 从./hooks导入{useFetch}; 功能页面道具{ 常量url=https://jsonplaceholder.typicode.com/posts +props.match.url; console.logurl; const[data
这里提供了一个沙盒,以获得更完整的示例:您的子组件重新渲染,但它使用了来自上一次渲染的旧数据。发生这种情况是因为在useEffect钩子中没有将url作为依赖项传递。如果您不想在其他地方使用它,最好将fetchUrl函数移到useffect中,因为现在eslint给出了一个错误: React Hook useEffect缺少依赖项:“fetchUrl”。包括它或删除依赖项数组。反应钩/详尽的DEP 下面是它的外观:
function useFetch(url) {
const [data, setData] = useState([]);
const [loading, setLoading] = useState(true);
useEffect(() => {
async function fetchUrl() {
const response = await fetch(url);
const json = await response.json();
setData(json);
setLoading(false);
}
fetchUrl();
}, [url]);
return [data, loading];
}
我不知道为什么,当我第一次访问动态页面时,console.logurl会被触发3次
发生这种情况的原因是组件重新加载了3次:
当它上升时
当钩子调用setDatajson时
当钩子调用setLoadingfalse时。
这里是一个工作示例:感谢您给出了这个非常有启发性的答案@Andrii我遇到了完全相同的问题,但在我的fetchData中,我将fetch函数作为“fetchFunction”传递,直接替换本例中的“fetchurl”。如果我将fetchFunction函数放在dependencies数组中,那么它将创建一个有限循环。。有什么方法可以做到这一点吗?@Cedo你可以使用useMemo钩子来存储你的fetch函数。下面是useFetchVersion2@AndriiGolubenko的一个例子,谢谢。我就是这么做的,但是有一个问题。它修复了无限循环。