gpt4 book ai didi

javascript - 使用 ReduxReducer 来合并数组

转载 作者:行者123 更新时间:2023-12-02 23:25:05 26 4
gpt4 key购买 nike

所以这里发生的是我正在尝试设置自动分页。我设置了一个 while 循环,在返回数据中的数组项数量大于 0 时发送 get 请求。每个循环都会将数据发送到我的 reducer AppendUserHistoryReducer,如下面的代码所示。

我希望发生的是, reducer 将其接收到的每个数据循环附加到单个数组中。就目前情况而言,我只弄清楚如何将每个数据循环存储在单独的状态数组中(如控制台图片所示)。我可以映射数据并将其全部合并在一起,但我只是想知道是否有更好的方法来做到这一点,因此不需要编写额外的代码。意思是,可以在reducer中完成吗?

需要明确的是,我的目标是让totalUserHistory状态为[0 - 729],而不是分解为不同的数组,只需修改reducer中的代码即可。

我正在寻求帮助的代码:

export const AppendUserHistoryReducer = (userData=[], action) => {
if (action.type === 'APPEND_USER_DATA') {
return [...userData.concat(action.payload)]
}
return userData;
}

While 循环代码,仅用于上下文:

  // auto pagination
while (this.props.userHistory.length > 0) {
let { userHistory } = this.props
let lastPage = userHistory[userHistory.length-1].data.name

const response = await axios.get (`https://oauth.reddit.com/user/${userIdentityObject.data.name}/saved/.json?limit=100&after=${lastPage}`, {
headers: { 'Authorization': `bearer ${token}` }
})
console.log('a loop');
this.props.storeUserHistory(response.data.data.children)
this.props.appendUserHistory(response.data.data.children)
}
}

在控制台中生成多个数组:

enter image description here

最佳答案

根据屏幕截图,您有一个包含所有项目的数组。它只是 chrome 开发工具在视觉上将数组分开以方便调试。

为了确保只有一个数组,可以将其字符串化,然后打印到控制台:

console.log(JSON.stringify(totalUserHistory))

关于javascript - 使用 ReduxReducer 来合并数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56780067/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com