Javascript 反应:Axios不';t发送到数据库
我有一个使用React的可拖动列表,它正在运行。现在我想在MYSQL数据库中注册被拖动元素的最终位置,并使用Laravel来管理后端和控制器 到目前为止,由于的原因,我成功地将所有数据都放在了正确的位置,但是当我使用Javascript 反应:Axios不';t发送到数据库,javascript,reactjs,Javascript,Reactjs,我有一个使用React的可拖动列表,它正在运行。现在我想在MYSQL数据库中注册被拖动元素的最终位置,并使用Laravel来管理后端和控制器 到目前为止,由于的原因,我成功地将所有数据都放在了正确的位置,但是当我使用axios.post时,新数据没有注册到我的数据库中 执行console.log({order})时&console.log(响应),数据确实修改如下: {order: Array(3)} order: Array(3) 0: {id: 2, order: 1} 1: {id: 3,
axios.post
时,新数据没有注册到我的数据库中
执行console.log({order})时代码>&console.log(响应)代码>,数据确实修改如下:
{order: Array(3)}
order: Array(3)
0: {id: 2, order: 1}
1: {id: 3, order: 2}
2: {id: 1, order: 3}
length: 3
__proto__: Array(0)
__proto__: Object
及
我的职能:
function handleOnDragEnd(result) {
if (!result.destination) return;
const items = Array.from(list);
let oldIndex = result.source.index;
let newIndex = result.destination.index;
const [reorderedItem] = items.splice(oldIndex, 1);
items.splice(newIndex, 0, reorderedItem);
setList(items);
console.log(oldIndex,newIndex)
console.log(items)
function handleChangeOrder(oldIndex, newIndex) {
if(oldIndex == newIndex){return ;}
const items = Array.from(list);
let newSequence = [];
items.forEach((item, index) => {
newSequence.push({ id: item.id, order: index + 1 });
});
changeSocialOrder(newSequence);
// console.log(newSequence)
}
async function changeSocialOrder(order){
try {
const response = await axios.post('http://localhost:8000/api/social/reorder/', {order});
console.log({order});
console.log(response);
return response.data;
} catch (error){
console.error("Not able");
}
}
我将我的函数传递给一个孩子,因此使用了props
,这意味着在onDragEnd
上两个函数都执行:
<DragDropContext onDragEnd={(result, oldIndex, newIndex)=>{ props.handleOnDragEnd(result); props.handleChangeOrder(oldIndex,newIndex) }}>
我的重新订购控制器:
public function reorder(Request $request)
{
$this->validate($request,['order'=>'required|array']);
$order = $request->input('order');
DB::transaction(function () use ($order){
foreach ($order as $value){
Social::find($value['id'])->update(['order'=>$value['order']]);
}
});
}
您能否编辑您的答案,并使用组件结构更清晰地编写代码,因为函数似乎不相关。@Eddster最初的组件很长,我尝试将其缩短。为了便于解释,handleOnDragEnd
是将最后一个拖动的元素设置到位,这样他就不会向后移动,handleChangeOrder
是设置数组中元素的新顺序,最后是changeSocialOrder
将结果发布到数据库。
Route::post('/social/reorder', [SocialController::class, 'reorder']);
public function reorder(Request $request)
{
$this->validate($request,['order'=>'required|array']);
$order = $request->input('order');
DB::transaction(function () use ($order){
foreach ($order as $value){
Social::find($value['id'])->update(['order'=>$value['order']]);
}
});
}