Javascript React Hook useEffect缺少依赖项-大小写:分页
我已经阅读了几个有关stackoverflow的案例,这些案例都是关于useEffect中缺少依赖项的: 例子: 现在的情况是,我使用useEffect进行分页: 以下是源代码: 反应路由器dom配置Javascript React Hook useEffect缺少依赖项-大小写:分页,javascript,reactjs,Javascript,Reactjs,我已经阅读了几个有关stackoverflow的案例,这些案例都是关于useEffect中缺少依赖项的: 例子: 现在的情况是,我使用useEffect进行分页: 以下是源代码: 反应路由器dom配置 { path: "/note", name: "My Note", exact: true, Component: Note }, 注意组件 const Note = (props) => { const getQueryParams =
{ path: "/note", name: "My Note", exact: true, Component: Note },
注意组件
const Note = (props) => {
const getQueryParams = () => {
return window.location.search.replace("?", "").split("&").reduce((r, e) => ((r[e.split("=")[0]] = decodeURIComponent(e.split("=")[1])), r),
{}
);
};
const MySwal = withReactContent(Swal);
const history = useHistory();
// Get Queries On URL
const { page: paramsPage, "per-page": paramsPerPage } = getQueryParams();
// Queries as state
const [queryPage, setQueryPage] = useState(
paramsPage === undefined ? 1 : paramsPage
);
const [queryPerPage, setQueryPerPage] = useState(
paramsPerPage === undefined ? 10 : paramsPerPage
);
// Hold Data Records as state
const [notes, setNotes] = useState({
loading: false,
data: [],
totalData: 0,
});
useEffect(() => {
console.log(queryPage, queryPerPage);
setNotes({
...notes,
loading: true,
});
// Fetching data from API
NoteDataService.getAll(queryPage, queryPerPage)
.then((response) => {
setNotes({
loading: false,
data: response.data,
totalData: parseInt(response.headers["x-pagination-total-count"]),
});
return true;
})
.catch((e) => {
MySwal.fire({
title: e.response.status + " | " + e.response.statusText,
text: e.response.data,
});
});
return false;
}, [queryPage, queryPerPage]);
const { loading, data, totalData } = notes;
...
所以这里有两个问题:
React Hook use Effect缺少依赖项:“MySwal”和“notes”。包括它们或删除依赖项数组。如果在“setNotes”调用中只需要“notes”,也可以执行功能更新“setNotes(n=>…)”。
如果我将notes和MySwal添加为依赖项,它会给我一个连续循环/note?Page=2&每页=10
,一切都很顺利。
但是,当返回到“/note”时,页面不会经历重新渲染。
奇怪的是,如果这样的路线/note?Page=1&每页=10
,返回结果完美。
分页后是否不运行useEffect
首先,将API调用移动到useEffect内部。获取数据后,可以更改状态
useEffect(() => {
//Fetch the data here
//setState here
},[]) //if this array is empty, you make the api call just once, when the `component mounts`
useEffect的第二个参数是依赖性数组,如果不传递它,useEffect将在每次渲染和更新中触发,这是不好的。如果你PARS一个空数组,那么它只进行一次调用,如果你传递一个值,那么只有当传递的值被更改时,react才会呈现。在useEffect
setNotes中替换你的第一个setNote(prevNotes=>({…prevNotes,loading:true}))
;你不需要使用有效的笔记。这只是一个问题。Oke,MySwal组件如何?``constmyswalref=useRef(null);const MySwal=withReactContent(Swal);useffect(()=>{MySwalRef.current=MySwal;},[MySwal]);//你的使用效果;useffect(()=>{NoteDataService.getAll(queryPage,queryPerPage).then().catch(()=>{MySwalRef.current.fire();});},[])```这是可行的,但我对useRef不太熟悉,让我先学习一下