[英]React function is showing that object is empty when I try to write it out to the console
I am using this constant function whenever an element in a sortable list is moved:每当移动可排序列表中的元素时,我都会使用这个常量 function :
const arrayMoveMutate = (array, from, to) => {
array.splice(
to < 0 ? array.length + to : to,
0,
array.splice(from, 1)[0]
);
};
const arrayMove = (array, from, to) => {
array = array.slice();
arrayMoveMutate(array, from, to);
return array;
};
const onSortEnd = React.useCallback(
({ oldIndex, newIndex }) => {
setPlayer(player =>
arrayMove(player, oldIndex, newIndex)
);
console.log('mock api POST to save new index positions: ', player);
console.log('oldIndex: ', oldIndex);
console.log('newIndex: ', newIndex);
},
[]
);
Here is the SortableList:这是可排序列表:
<SortableList player={player} onSortEnd={onSortEnd} />
Every time a move an element, I do see the oldIndex and newIndex in my console change.每次移动元素时,我都会在控制台中看到 oldIndex 和 newIndex 发生变化。
However, 'player' is always empty.但是,“播放器”始终为空。
How would I pass the 'player' object to onSortEnd so that I can do my api POST?如何将“播放器” object 传递给 onSortEnd 以便我可以进行 api POST?
thanks!谢谢!
player
in the console.log
statement is a reference to the hook value created in your useState
hook. console.log
语句中的player
是对在useState
挂钩中创建的挂钩值的引用。 Hence add it to the callbacks deps as below to get the fresh value, else it will always be empty within the callback:因此,将其添加到如下回调 deps 以获得新值,否则在回调中它将始终为空:
const onSortEnd = React.useCallback(({ oldIndex, newIndex }) => {
setPlayer(player => arrayMove(player, oldIndex, newIndex));
console.log("mock api POST to save new index positions: ", player);
console.log("oldIndex: ", oldIndex);
console.log("newIndex: ", newIndex);
}, [player]);
That said, this deps is only required for logging the value inside the callback.也就是说,这个 deps 仅用于记录回调中的值。 As you are passing function to setPlayer
, it will always take the latest value of the state irrespective of the deps.当您将 function 传递给setPlayer
时,它将始终采用 state 的最新值,而与部门无关。 Hence the state should be setting fine even with your code.因此,即使使用您的代码,state 也应该设置得很好。 If still facing issues, try setting the deps and try again.如果仍然遇到问题,请尝试设置部门并重试。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.