为什么useState反应钩子导致太多重新渲染。 React限制了渲染次数以防止无限循环

时间:2020-04-23 02:46:23

标签: javascript reactjs react-hooks

我有以下脚本

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);
  }

1 个答案:

答案 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状态更改时运行。