Hook 不会重新渲染组件
Hook doesn't rerender component
我将 React 与 React-Router-Dom 一起使用,但我不知道为什么我的子组件(功能组件)在 URL 更改时不重新呈现。而且我不知道为什么,当我第一次访问动态页面时,console.log(url)
触发了 3 次?
我的子组件:
import React from "react";
import { useFetch } from "./hooks";
function Page(props) {
const url = "https://jsonplaceholder.typicode.com/posts" + props.match.url;
console.log(url);
const [data, loading] = useFetch(url);
return (
<>
{loading ? (
"Loading..."
) : (
<>
<h1>{data.title}</h1>
<p>{data.body}</p>
</>
)}
</>
);
}
export default Page;
此处提供沙箱以提供更完整的示例:https://codesandbox.io/embed/great-mahavira-5ktrk
您的子组件 re-renders,但它使用了之前渲染的旧数据。发生这种情况是因为您没有将 url
作为 useEffect
挂钩中的依赖项传递。并且最好将fetchUrl
函数移到useEffect
里面(如果你不想在其他地方使用它的话),因为现在eslint
会报错:
React Hook useEffect has a missing dependency: 'fetchUrl'. Either include it or remove the dependency array. (react-hooks/exhaustive-deps)
它应该是这样的:
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];
}
"And I don't know why, when I visit a dynamic page for the first time, the console.log(url)fired 3 times ?"
发生这种情况是因为您的组件重新呈现 3 次:
挂载时。
当你的 hook 调用时 setData(json)
.
- 当你的 hook 调用时
setLoading(false)
.
此处工作示例:https://codesandbox.io/embed/condescending-wildflower-v8m4c
我将 React 与 React-Router-Dom 一起使用,但我不知道为什么我的子组件(功能组件)在 URL 更改时不重新呈现。而且我不知道为什么,当我第一次访问动态页面时,console.log(url)
触发了 3 次?
我的子组件:
import React from "react";
import { useFetch } from "./hooks";
function Page(props) {
const url = "https://jsonplaceholder.typicode.com/posts" + props.match.url;
console.log(url);
const [data, loading] = useFetch(url);
return (
<>
{loading ? (
"Loading..."
) : (
<>
<h1>{data.title}</h1>
<p>{data.body}</p>
</>
)}
</>
);
}
export default Page;
此处提供沙箱以提供更完整的示例:https://codesandbox.io/embed/great-mahavira-5ktrk
您的子组件 re-renders,但它使用了之前渲染的旧数据。发生这种情况是因为您没有将 url
作为 useEffect
挂钩中的依赖项传递。并且最好将fetchUrl
函数移到useEffect
里面(如果你不想在其他地方使用它的话),因为现在eslint
会报错:
React Hook useEffect has a missing dependency: 'fetchUrl'. Either include it or remove the dependency array. (react-hooks/exhaustive-deps)
它应该是这样的:
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];
}
"And I don't know why, when I visit a dynamic page for the first time, the console.log(url)fired 3 times ?"
发生这种情况是因为您的组件重新呈现 3 次:
挂载时。
当你的 hook 调用时
setData(json)
.- 当你的 hook 调用时
setLoading(false)
.
此处工作示例:https://codesandbox.io/embed/condescending-wildflower-v8m4c