React+Inertia+Laravel步骤流:POST请求后获文档ID不重渲染组件
解决方案
1. 后端返回文档ID
不要使用Inertia::render(会重置页面props导致空白),改用以下两种方式返回文档ID:
方式一:通过Flash数据返回(保留页面状态)
修改后端代码,创建文档成功后,将document_id加入返回数据:
$document_data = $request->all(); if($document_data['step_no'] === 0){ if($document_data['parent_cat_type'] == 'policy'){ $cat_id = $this->createPolicyCategory($document_data['cat_name']); if ($cat_id !== 500) { $document_id = $this->createDocumentAndCategory($document_data, $cat_id,'draft','policy'); $categories = Categories::where('cat_parent_cat_id', null)->get(); $projects = Projects::all(); // 携带文档ID返回原页面 return back()->with([ 'document_id' => $document_id, 'categories' => $categories, 'projects' => $projects, ]); }else { return back()->with(['error' => 'Category already exists']); } }else { $document_id = $this->createDocumentAndCategory($document_data,'','draft','project'); return back()->with(['document_id' => $document_id]); } }elseif ($document_data['step_no'] === 1) { // 步骤2更新逻辑,使用document_id修改文档 }elseif ($document_data['step_no'] === 2) { // 步骤3更新逻辑 }
方式二:直接返回JSON响应(无需刷新页面)
如果不需要刷新页面,直接返回JSON格式的文档ID:
// 创建文档成功后 return response()->json([ 'document_id' => $document_id, 'success' => true ]);
2. 前端获取并保存文档ID
根据后端返回方式,在前端获取ID并保存到组件状态/全局上下文,供后续步骤使用:
方式一:获取Flash数据(对应后端back()方式)
使用Inertia的usePage()钩子读取flash数据:
import { usePage } from '@inertiajs/react'; import { useState } from 'react'; const YourComponent = () => { const [documentId, setDocumentId] = useState(null); const { props } = usePage(); const onFormSave = (step) => { if (stepOneParentCategory == '1'){ try { Inertia.post('/save-document', { doc_policy_content: stepTwoPolicyEditorContent, doc_framework_content: valueFrameworkEditor, cat_name: stepOneNewCategory , doc_user_id: "1" , parent_cat_type:'policy' , step_no: step }, { onSuccess: () => { // 从flash数据中提取文档ID const id = props.flash.document_id; setDocumentId(id); console.log('文档ID:', id); }, }); } catch (error) { console.error('保存文档失败:', error); } } else if (stepOneParentCategory == '2') { Inertia.post('/save-document', { doc_policy_content: stepTwoPolicyEditorContent, doc_framework_content: valueFrameworkEditor , doc_user_id: "1" , project_id: stepOneProjectId , parent_cat_type:'project', step_no: step }, { onSuccess: () => { const id = props.flash.document_id; setDocumentId(id); } }); } } // 组件渲染逻辑... }
方式二:获取JSON响应(对应后端response()->json方式)
在onSuccess回调中直接读取响应数据:
const [documentId, setDocumentId] = useState(null); const onFormSave = (step) => { if (stepOneParentCategory == '1'){ try { Inertia.post('/save-document', { // 请求参数 }, { onSuccess: (response) => { const id = response.data.document_id; setDocumentId(id); console.log('文档ID:', id); }, }); } catch (error) { console.error('保存文档失败:', error); } } // 其他分支同理 }
3. 后续步骤使用文档ID
在步骤2、3的更新请求中,将保存的documentId作为参数传入:
const onStepTwoSave = () => { Inertia.post('/update-document', { document_id: documentId, // 其他需要更新的字段 step_no: 1 }); }
内容的提问来源于stack exchange,提问作者Shivank sagar
相关产品推荐
相关产品推荐

