Node.js向React传递数据 解决axios查询结果无法在editPage加载问题
核心结论
你需要在editPage前端再次发起请求获取对应数据,当前的实现逻辑存在上下文丢失的问题:listPage 中发起的 axios.post 请求的返回数据仅存在于 listPage 的运行上下文,执行 window.location 页面跳转后,旧页面的所有内存数据会被完全清空,新加载的 editPage 无法访问前一页的请求返回结果。
问题根因
- 你当前的 listPage 代码中,axios.post 的 then 回调没有接收后端返回的结果数据,就算不跳转也无法拿到查询到的文档内容
- 页面跳转属于整页刷新/上下文替换,前一页的请求结果不会自动传递到新页面
推荐实现方案
建议通过URL携带文档ID,editPage 加载后主动拉取对应数据,该方案支持用户直接收藏/分享编辑页链接,可用性更高。
修改listPage代码
删除跳转前的冗余post请求,直接将ID拼接在跳转URL中:
const editById = (id) => { console.log(id); // 将ID带入跳转URL,可根据你的路由规则调整为路径参数或query参数 window.location = `/admin/services/${id}`; };
调整后端接口(可选优化)
将查询接口改为GET请求更符合资源查询的语义,同时支持路径参数传参:
app.get('/getDocToEdit/:id', (req, res) => { const id = req.params.id; ServicesModel.findOne({_id: id}, function(err,result) { if (err) return res.status(500).send(err); console.log(result); res.status(200).send(result) }); })
editPage侧新增数据拉取逻辑
页面加载完成后从URL中提取ID,发起请求拉取数据后渲染到页面:
// 页面挂载完成后触发请求,框架项目可对应写在生命周期钩子中 window.addEventListener('load', async () => { // 从URL路径中提取文档ID,可根据你的实际路由规则调整提取逻辑 const pathArr = window.location.pathname.split('/'); const docId = pathArr[pathArr.length - 1]; try { const { data } = await axios.get(`/getDocToEdit/${docId}`); // 此处将data赋值给表格绑定的变量,触发页面渲染即可 console.log('待编辑文档数据:', data); } catch (error) { console.log('拉取文档数据失败:', error); } })
备用实现方案
如果不想修改后端接口,也可以将跳转前请求拿到的文档数据存在sessionStorage中,跳转后从本地存储读取:
// listPage 代码修改 const editById = (id) => { console.log(id); axios .post(`/getDocToEdit`, { id: id }) .then((res) => { console.log(id, " worked"); // 将返回数据存入sessionStorage,跳转后读取 sessionStorage.setItem('editDoc', JSON.stringify(res.data)); window.location = "/admin/services/:site"; }) .catch((error) => { console.log(error); }); }; // editPage 读取逻辑 window.addEventListener('load', () => { const editDoc = JSON.parse(sessionStorage.getItem('editDoc')); if (editDoc) { // 渲染数据到页面 console.log('待编辑文档数据:', editDoc); // 读取完成后删除存储,避免残留旧数据 sessionStorage.removeItem('editDoc'); } else { // 无数据的兜底逻辑,比如跳转回列表页 window.location = '/listPage' } })
内容的提问来源于stack exchange,提问作者Gianluca
相关产品推荐
相关产品推荐

