我有以下脚本
const [customers, setCustomer] = useState([]);
if(users.results){
users.results.filter(user => {
user.roles.filter(role => {
if(role.role.name === 'ADMIN'){
admins.push(user);
}
});
});
let x = []
users.results.filter(user => {
user.roles.filter(role => {
if (role.role.name === 'CUSTOMER') {
x.push(user);
}
});
});
setCustomer(x);
}
尝试调用setCustomer
会导致重新渲染过多。 React限制了渲染次数,以防止无限循环。。我似乎找不到原因。
如何将客户设置为x
的值而不会导致上述错误?
更新代码
const Administration = props =>{
const { fetchUsers, users, loading_users } = props;
const usersPerPage = 9
useEffect(() => {
fetchUsers();
}, []);
let admins = [];
const [customers, setCustomer] = useState([]);
if(users.results){
users.results.filter(user => {
user.roles.filter(role => {
if(role.role.name === 'ADMIN'){
admins.push(user);
}
});
});
let x = []
users.results.filter(user => {
user.roles.filter(role => {
if (role.role.name === 'CUSTOMER') {
x.push(user);
}
});
});
setCustomer(x);
}
答案 0 :(得分:1)
听起来setCustomer
更新时,您只想用users
更新客户。通过将useEffect
放在users
中作为“仅在此更改时才调用”选项,可以为您做到这一点。看起来admins
应该是状态:
const [admins, setAdmins] = useState([]);
useEffect(() => {
if(users.results){
let admins = [];
users.results.filter(user => {
user.roles.filter(role => {
if(role.role.name === 'ADMIN'){
admins.push(user);
}
});
});
setAdmins(admins);
let x = []
users.results.filter(user => {
user.roles.filter(role => {
if (role.role.name === 'CUSTOMER') {
x.push(user);
}
});
});
setCustomer(x);
}
}, [users]);
现在,此操作仅在挂载时和users
状态更改时运行。