Reactjs (重构/改进)循环进行API调用,并在;“无循环函数”;

Reactjs (重构/改进)循环进行API调用,并在;“无循环函数”;,reactjs,eslint,do-while,Reactjs,Eslint,Do While,尽管在stackoverflow上查看并遵循了大量答案,我仍然未能重构此代码以遵守ESLint no loop funct 尽管我努力重构代码,但仍不断收到以下警告: import React from 'react'; import { apiFullCall } from '../../apiHelper'; const MyComponent = props => { const [state, setState] = React.useState({ total: 0, b

尽管在stackoverflow上查看并遵循了大量答案,
我仍然未能重构此代码以遵守
ESLint no loop funct

尽管我努力重构代码,但仍不断收到以下警告:

import React from 'react';
import { apiFullCall } from '../../apiHelper';

const MyComponent = props => {

  const [state, setState] = React.useState({ total: 0, biologyBooksByAuthor: [] });
  let isLoaded = React.useRef(true);

  const token = sessionStorage.getItem('token');
  const authorID = sessionStorage.getItem('author_id');
  
  const getBooks = async() => { // fetch items

    let page = 1;
    let scienceBooks, biologyBooks; 

    // create empty arrays to store book objects for each loop
    let scienceBooks = biologyBooks = [];

    // create a lastResult object to help check if there is a next page
    let lastResult = { next: null };


    do { // the looping - this is what I have failed to refactor
      try {
        await apiFullCall( // Make API calls over paginated records
          '', 
          token, 
          'get', 
          `books/?author_id=1&page=${page}` 
        ).then(res => {
          if (res) {
            const { status, body } = res;

            if (status === 200 || status === 201) {
              
              lastResult = body; // assign lastResult to pick "next"
    
              body && 
                body.results && 
                  body.results.map(eachBook => { // we map() over the returned "results" array

                      // the author with queried "author_id" writes science books; 
                      // so we add each book (an object) into the science category

                      scienceBooks.push(eachBook);

                      // We then filter the author's biology books (from other science books)

                      biologyBooks = scienceBooks.filter(
                        ({ is_biology }) =>
                          typeof(is_biology) === "boolean" && is_biology === true
                      );

                      return null;
                    }
              );

              // increment the page with 1 on each loop
              page++;
            }
          }
        }).catch(error => console.error('Error while fetching data:', error));

      } catch (err) { console.error(`Oops, something went wrong ${err}`); }

      // keep running until there's no next page
    } while (lastResult.next !== null);

    // update the state
    setState(prevState => ({
      ...prevState, total: scienceBooks.length, biologyBooksByAuthor: biologyBooks,
    }));
  };
  
  React.useEffect(() => { // fetch science books by author (logged in)

    if (isLoaded && authorID) {
      getBooks();
    };
    
    return function cleanup() {...}; // clean up API call, on unmount

  }, [isLoaded, authorID]);

  return (
     // render the JSX code
  );

}
编译时带有警告。
循环中声明的函数包含对变量“lastResult”、“biologyBooks”、“page”的不安全引用无循环函数
代码如下:

import React from 'react';
import { apiFullCall } from '../../apiHelper';

const MyComponent = props => {

  const [state, setState] = React.useState({ total: 0, biologyBooksByAuthor: [] });
  let isLoaded = React.useRef(true);

  const token = sessionStorage.getItem('token');
  const authorID = sessionStorage.getItem('author_id');
  
  const getBooks = async() => { // fetch items

    let page = 1;
    let scienceBooks, biologyBooks; 

    // create empty arrays to store book objects for each loop
    let scienceBooks = biologyBooks = [];

    // create a lastResult object to help check if there is a next page
    let lastResult = { next: null };


    do { // the looping - this is what I have failed to refactor
      try {
        await apiFullCall( // Make API calls over paginated records
          '', 
          token, 
          'get', 
          `books/?author_id=1&page=${page}` 
        ).then(res => {
          if (res) {
            const { status, body } = res;

            if (status === 200 || status === 201) {
              
              lastResult = body; // assign lastResult to pick "next"
    
              body && 
                body.results && 
                  body.results.map(eachBook => { // we map() over the returned "results" array

                      // the author with queried "author_id" writes science books; 
                      // so we add each book (an object) into the science category

                      scienceBooks.push(eachBook);

                      // We then filter the author's biology books (from other science books)

                      biologyBooks = scienceBooks.filter(
                        ({ is_biology }) =>
                          typeof(is_biology) === "boolean" && is_biology === true
                      );

                      return null;
                    }
              );

              // increment the page with 1 on each loop
              page++;
            }
          }
        }).catch(error => console.error('Error while fetching data:', error));

      } catch (err) { console.error(`Oops, something went wrong ${err}`); }

      // keep running until there's no next page
    } while (lastResult.next !== null);

    // update the state
    setState(prevState => ({
      ...prevState, total: scienceBooks.length, biologyBooksByAuthor: biologyBooks,
    }));
  };
  
  React.useEffect(() => { // fetch science books by author (logged in)

    if (isLoaded && authorID) {
      getBooks();
    };
    
    return function cleanup() {...}; // clean up API call, on unmount

  }, [isLoaded, authorID]);

  return (
     // render the JSX code
  );

}
请注意,我实际上在“do while”之外声明了上述变量
lastResult
biologyBooks
page


任何帮助或线索都将不胜感激。

警告所指的函数是
。然后
回调,如果您使用
异步/wait
坚持,请尝试删除
。然后将结果分配给一个变量,并删除不必要的
.map
部分,您可以使用扩展运算符或
.concat
连接以前的结果

从“React”导入React;
从“../../apiHelper”导入{apiFullCall};
常量MyComponent=props=>{
常量[状态,设置状态]=React.useState({
总数:0,
scienceBooksByAuthor:[],
});
const isLoaded=React.useRef(true);
const token=sessionStorage.getItem('token');
const authorID=sessionStorage.getItem('author_id');
const getBooks=async()=>{
//取货
设page=1;
让科学书籍=[];
//创建lastResult对象以帮助检查是否有下一页
让lastResult={next:null};
做{
//循环——这就是我未能重构的东西
试一试{
const res=wait apiFullCall(
//对分页记录进行API调用
'',
代币
“得到”,
`books/?author\u id=1&page=${page}`,
);
如果(res){
const{status,body}=res;
如果(状态===200 | |状态===201){
lastResult=body;//将lastResult分配给拾取“下一步”
//连接新结果
科学书籍=[
…科学书籍,
…((lastResult&&lastResult.results)| |[]),
];
//在每个循环中增加一个页面
页码+=1;
}
}
}捕捉(错误){
error(`Oops,出了点问题${err}`);
}
//继续运行直到没有下一页
}while(lastResult.next!==null);
const biologyBooks=scienceBooks.filter(
({is_biology})=>
typeof is_biology==='boolean'&&is_biology===true,
);
//更新状态
设置状态(prevState=>({
…国家,
总计:scienceBooks.length,
scienceBooks作者:scienceBooks,
}));
};
React.useffect(()=>{
//按作者获取科学书籍(已登录)
如果(isLoaded&&authorID){
getBooks();
}
返回函数cleanup(){…};//卸载时清除API调用
},[isLoaded,authorID]);
返回(
//呈现JSX代码
);
};

Hi,已接近-警告仍然存在。好消息是它从警告列表中删除了
lastResult
page
。所以基本上我们仍然被警告关于
biologyBooks
变量。关于如何消除这个问题还有什么想法吗?@MwamiTovi我用一个完整的重构更新了我的答案,
map
是不必要的,因为你只需要连接结果,我在获取所有结果后移动了生物学书籍的过滤器,因为一旦你拥有了所有的书籍,这样做更有意义哇,它工作起来很有魅力。因此,罪魁祸首是
map()
。。谢谢仅供参考:我更新了这个
状态
字段-
biologyBooksByAuthor:biologyBooks
这就是我需要过滤器的原因。