将 axios 的 Get 请求的结果放入数组

发布于 2025-01-10 00:19:26 字数 3098 浏览 1 评论 0原文

我不明白一个非常简单的任务,我用 React 中的 axios 从 API 发出了请求。 如果我通过控制台记录 res.data,就像控制台上单个对象的 170 个结果一样。

我需要将所有这些结果转换为单个对象数组。

这是一项基本任务,但我不明白如何去做。

该应用程序是 Trello 克隆。

我有一个名为 board 的变量,它包含所有数据,通过此列表请求,我抓取 trello 的所有列并附加到 newBoardData 中的 ListObjects [] (它是 board 的克隆)

这是我的代码:

//Get Request

const getList = async (id) => {
  try {
  return await axios.get(`${ENDPOINT}/lists/${id}`);
  } catch (err) {
    console.log(err);
  }
};



  const [loading, setLoading] = useState(false);
  // Use Effect for grab the data with the listId 

  useEffect(() => {
      (async () => {
          setLoading(true);
          const res = await (getList(listId));
          //Loading up the listObjects
           const oldList = board.board.listObjects
           const newList = []
          const payload = res.data;
           //Adding all the old values to the new list (except for the current payload id)
          for(let obj of oldList){
          if(obj._id !== payload._id) newList.push(obj)
           } 
             //Adding the current payload id
           newList.push(payload)  
          const data = {
            ...board,
            board: {...board.board, listObjects: newList}
          };
          setList(res.data);

          // Here I put the data objects with the new ListObjects Array
          setBoardNew(data);

          setLoading(false);
      })();
  }, []);

这是控制台日志获取请求的res.data:

res.data的console.log

这里是board对象:

board object

可以看到ListObjects中当前res.data存在垃圾结果

我认为它对每个列表中的每张卡都提出了请求。

非常感谢!

更新:

我将解释该应用程序的工作原理:

我有一个名为 Board.js 的文件,我在其中进行此调用(在控制台日志中,如果我有两列,我有两个调用):

    try {
    return await axios.get(`${ENDPOINT}/boards/${id}`);
    } catch (err) {
      console.log(err);
    }
  };

  useEffect(() => {
      (async () => {
          setLoading(true);
          const res = await (getUserBoard(match.params.id));
          if (res) {
            axios.defaults.headers.common['boardId'] = match.params.id;
            
          } else {
            delete axios.defaults.headers.common['boardId'];
          }
          
          const payload = { ...res.data, listObjects: [], cardObjects: [] };
          const data = {
            ...state,
            board: { ...state.board, ...payload },
          };
          setBoardData(data);
          setLoading(false);
      })();
  }, []);

然后我将道具数据发送到文件 List .js

 {board.board.lists.map((listId, index) => (
               
                  <List key={listId} listId={listId} index={index} board={board} />

列表文件发送数据到 card.js

 {list.cards.map((cardId, index) => (
                    <Card key={cardId} cardId={cardId} list={list} index={index} board={boardNew} />

逻辑是:有板(board.js),板上有列表(列)(list.js),列表中有卡片(card.js)

我希望它更清楚。

I don't understand a very simple task, I made a request from a API with axios in react.
If I console log the res.data, is like 170 result of single objects on my console.

I need to convert all these result in a single array of objects.

It's a basic task but I don't understand how to do it.

The application is a Trello Clone.

I have a variable called board that has all the data and with this list request, I grab all the column the the trello and append to ListObjects [] in newBoardData (it's a clone of board)

Here is my code:

//Get Request

const getList = async (id) => {
  try {
  return await axios.get(`${ENDPOINT}/lists/${id}`);
  } catch (err) {
    console.log(err);
  }
};



  const [loading, setLoading] = useState(false);
  // Use Effect for grab the data with the listId 

  useEffect(() => {
      (async () => {
          setLoading(true);
          const res = await (getList(listId));
          //Loading up the listObjects
           const oldList = board.board.listObjects
           const newList = []
          const payload = res.data;
           //Adding all the old values to the new list (except for the current payload id)
          for(let obj of oldList){
          if(obj._id !== payload._id) newList.push(obj)
           } 
             //Adding the current payload id
           newList.push(payload)  
          const data = {
            ...board,
            board: {...board.board, listObjects: newList}
          };
          setList(res.data);

          // Here I put the data objects with the new ListObjects Array
          setBoardNew(data);

          setLoading(false);
      })();
  }, []);

Here is the console log of the get request res.data:

console.log of res.data

here is the board object:

board object

You can saw that there is a spam of result with the current res.data in ListObjects

I'think it make a request for every card in every list.

thank you very much!

UPDATE:

I will explain how the app works:

I have a file called Board.js, where I make this call (in the console log I have two call if I have two columns):

    try {
    return await axios.get(`${ENDPOINT}/boards/${id}`);
    } catch (err) {
      console.log(err);
    }
  };

  useEffect(() => {
      (async () => {
          setLoading(true);
          const res = await (getUserBoard(match.params.id));
          if (res) {
            axios.defaults.headers.common['boardId'] = match.params.id;
            
          } else {
            delete axios.defaults.headers.common['boardId'];
          }
          
          const payload = { ...res.data, listObjects: [], cardObjects: [] };
          const data = {
            ...state,
            board: { ...state.board, ...payload },
          };
          setBoardData(data);
          setLoading(false);
      })();
  }, []);

Then I send the props data to the file List.js

 {board.board.lists.map((listId, index) => (
               
                  <List key={listId} listId={listId} index={index} board={board} />

The list file send the data to
card.js

 {list.cards.map((cardId, index) => (
                    <Card key={cardId} cardId={cardId} list={list} index={index} board={boardNew} />

The logic is: There is the board(board.js), in the board there are the lists (column)(list.js) in the lists there are the cards (card.js)

I hope it's more clear.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

别挽留 2025-01-17 00:19:26

简单地使用这种方法将新的 id 值添加到数组状态中。

this.setState({ myArray: [...this.state.myArray, 'new value'] }) //simple value
this.setState({ myArray: [...this.state.myArray, ...[1,2,3] ] }) //another array

simple use this approach to add your new id value into the array state.

this.setState({ myArray: [...this.state.myArray, 'new value'] }) //simple value
this.setState({ myArray: [...this.state.myArray, ...[1,2,3] ] }) //another array
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文