react:18.2.0
next:13.4.19(app router)
需求:需要一进入页面就请求列表接口,根据接口保存两个值,一个是列表list,一个数据总数total;
目前实现:
"use client";
import styles from "./permission.module.scss";
import pageTitle from "@hook/pageTitle/pageTitle";
import pageFilter from "./components/pageFilter/pageFilter";
import pageMain from "./components/pageMain/pageMain";
import pageDialog from "./components/pageDialog/pageDialog";
import { useEffect, useState } from "react";
import { permissionListApi } from "@api/permission-management/permission";
type FieldType = {
name?: string;
level?: number;
};
const defaultPagination = { current: 1, pageSize: 10, showQuickJumper: true, showSizeChanger: true, showTotal: (total: number) => `共 ${total} 条`, total: 0 };
export default function PermissionPage() {
let [pagination, setPagination] = useState(defaultPagination);
let [modalVisible, setModalVisible] = useState(false);
let [loading, setLoading] = useState(true);
let [list, setList] = useState([]);
// 获取列表
const getPermissionList = () => {
setLoading(true);
permissionListApi()
.then(res => {
if (res.code === 0) {
setList(res.data.list);
setPagination({ ...pagination, total: res.data.count });
}
})
.finally(() => {
setLoading(false);
});
};
useEffect(() => {
getPermissionList();
}, []);
// 筛选
const onFilter = (e: FieldType) => {
console.log(e);
};
// 新增
const onCreate = () => {
setModalVisible(true);
};
// 弹窗-取消
const onCancel = () => {
setModalVisible(false);
};
// 弹窗-确定
const onOk = () => {
setModalVisible(false);
};
return (
<div className={styles.container}>
{pageTitle("权限管理")}
{pageFilter(onFilter)}
{pageMain({ loading, list, pagination, onFilter, onCreate })}
{pageDialog({ modalVisible, onCancel, onOk })}
</div>
);
}
问题:
1、接口请求了两次,了解因为严格模式,执行了两次,但是我试了清除副作用,也还是执行了两次;
2、useEffect第二个参数[]有一个eslint的警告,这个警告只要加上setPagination就会有,去除就没有了:;
网上搜索尝试了在useEffect定义一个布尔变量然后return清除改变这个布尔,但是还是执行了两次;react本来就不熟,这次弄的时候官网推荐这个next搭建就更头疼了,react领域小白白
有没有懂的解释解答一下
1、你的ignore声明位置有问题,你在useEffect内部声明,每次都是一个新的变量,值都是false,必然会走if里面的语句,你应该放到useEffect外面声明,共用一个变量
2、参考https://www.jb51.net/article/268969.htm