Reactjs v17,axios,react-路由器-dom v6.
钩子useFetchAndLoad执行4次渲染。
我知道有两种呈现,第一种是加载组件,然后是useEffect。但另外两个人呢?然后我读到让渲染它四次。删除StricMode,但它仍然呈现4次。
我想我有它:加载组件、useEffect、response.data、setLoading(false)。这里有4幅渲染图。这是对的?
问:渲染四次可以吗?
import axios from "axios";
import { useEffect, useState } from "react";
export function useFetchAndLoad(id) {
const [response, setResponse] = useState({});
const [error, setError] = useState(null);
const [loading, setLoading] = useState(false);
useEffect(() => {
const controller = new AbortController();
const llamarEndPoint = async () => {
setLoading(true);
try {
const response = await axios.get(`https://rickandmortyapi.com/api/character/${id}`, { signal: controller.signal });
setResponse(response.data);
} catch (error) {
setError(error.message);
} finally {
setLoading(false);
}
}
llamarEndPoint();
return () => {
setLoading(false);
controller.abort();
}
}, [id]);
console.log(response)
if (response ) {
}
return { loading, response, error };
} import React, {
} from 'react'
import {
Link,
Outlet,
useLocation,
} from 'react-router-dom';
const RickAndMorty = () => {
const location = useLocation();
console.log(location);
// console.log("4 Links")
return (
<div>
<h1>Rick and Morty</h1>
<ul>
<li><Link to="1">Rick</Link></li>
<li><Link to="2">Morty</Link></li>
<li><Link to="3">3otro</Link></li>
<li><Link to="4">4otro</Link></li>
</ul>
<article>
<Outlet />
</article>
</div>
)
}
export default RickAndMorty import {useParams} from 'react-router-dom';
import { useFetchAndLoad } from '../../hook/useFetchAndLoad';
const Api = () => {
const params = useParams();
const id = parseInt(params.id);
const { loading, response, error } = useFetchAndLoad(id);
return (
<article>
<h1>Api</h1>
{loading ? <p>Loading...</p> : response.name ?? error}
</article>
)
}
export default Api; useFetchAndLoad.js:36 {}
useFetchAndLoad.js:36 {}
useFetchAndLoad.js:36 {id: 2, name: 'Morty Smith'}
useFetchAndLoad.js:36 {id: 2, name: 'Morty Smith'}发布于 2022-03-31 06:01:17
你没有记录loading,但我最好的猜测是,如果你是,你会看到
useFetchAndLoad.js:36 loading = false {}
useFetchAndLoad.js:36 loading = true {}
useFetchAndLoad.js:36 loading = true {id: 2, name: 'Morty Smith'}
useFetchAndLoad.js:36 loading = false {id: 2, name: 'Morty Smith'}所以是的,一切都很正确。
https://stackoverflow.com/questions/71685619
复制相似问题