给定数组 A,将其与 React useState 对象内的数组 B 连接起来
Given an array A, concatenate it with an array B inside an object of React useState
我在 React 中实现无限滚动,我必须调用后端 API 来获取下一页的内容。但是,我已将 useState 设置为一个对象。并且想更新对象里面的数组。
我知道这可以通过将结果设置为 useState 并为“下一个”和“上一个”添加额外的 useState 来轻松解决;但是,我想找到如何在当前条件下解决这个问题。
还请建议哪一个是最佳方式(一个 useState
我有一个使用下面给出的数据初始化的 React useState 挂钩
{
"count": 2,
"next": 2,
"previous": null,
"results": [
{
'id': 1,
'name': 'test1'
},
{
'id': 2,
'name': 'test2'
}
]
}
我得到的新数据的形式是
data = {
"count": 2,
"next": null,
"previous": 1,
"results": [
{
'id': 3,
'name': 'test3'
},
{
'id': 4,
'name': 'test4'
}
]
}
如何连接两个数组并更新状态,以获得类似这样的结果
{
"count": 2,
"next": null,
"previous": 1,
"results": [
{
'id': 1,
'name': 'test1'
},
{
'id': 2,
'name': 'test2'
},
{
'id': 3,
'name': 'test3'
},
{
'id': 4,
'name': 'test4'
}
]
}
假设你的状态变量被命名为 state
,你会做这样的事情:
setState({
...state,
next: null,
previous: 1,
results: [
...state.results,
{
'id': 3,
'name': 'test3'
},
{
'id': 4,
'name': 'test4'
}
]
})
我在 React 中实现无限滚动,我必须调用后端 API 来获取下一页的内容。但是,我已将 useState 设置为一个对象。并且想更新对象里面的数组。
我知道这可以通过将结果设置为 useState 并为“下一个”和“上一个”添加额外的 useState 来轻松解决;但是,我想找到如何在当前条件下解决这个问题。
还请建议哪一个是最佳方式(一个 useState
我有一个使用下面给出的数据初始化的 React useState 挂钩
{
"count": 2,
"next": 2,
"previous": null,
"results": [
{
'id': 1,
'name': 'test1'
},
{
'id': 2,
'name': 'test2'
}
]
}
我得到的新数据的形式是
data = {
"count": 2,
"next": null,
"previous": 1,
"results": [
{
'id': 3,
'name': 'test3'
},
{
'id': 4,
'name': 'test4'
}
]
}
如何连接两个数组并更新状态,以获得类似这样的结果
{
"count": 2,
"next": null,
"previous": 1,
"results": [
{
'id': 1,
'name': 'test1'
},
{
'id': 2,
'name': 'test2'
},
{
'id': 3,
'name': 'test3'
},
{
'id': 4,
'name': 'test4'
}
]
}
假设你的状态变量被命名为 state
,你会做这样的事情:
setState({
...state,
next: null,
previous: 1,
results: [
...state.results,
{
'id': 3,
'name': 'test3'
},
{
'id': 4,
'name': 'test4'
}
]
})