You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

添加location.assign('AllBlog')后数据无法提交,移除则正常,求助

问题解决:添加location.assign后无法提交数据

问题根源

你当前的代码里,axios.post是异步操作,调用后会立刻执行setPostDone(true),紧接着页面跳转,这时候POST请求还没来得及完成就被中断了,所以数据根本没传到后端。

解决方案

要确保axios请求成功完成后再触发页面跳转,同时用React规范的方式处理状态变化后的跳转逻辑:

  1. 把状态更新放在请求成功的回调里:只有当POST请求成功返回后,再设置PostDone为true。
  2. 用useEffect监听状态变化执行跳转:避免在组件函数体中直接执行DOM操作,这是React的最佳实践。

修改后的完整代码

import React, { useState, useEffect } from 'react'
import './PostBlog.css'
import axios from 'axios'

function PostBlog() {
    const [title, setTitle] = useState(null);
    const [body, setBody] = useState(null);
    const [PostDone, setPostDone] = useState(false);

    const handelPost = () => {
        axios.post('http://127.0.0.1:7000/postBlog', {
            title: title,
            body: body
        })
        // 请求成功后再更新状态
        .then(() => {
            setPostDone(true);
        })
        // 新增错误处理,方便排查问题
        .catch(error => {
            console.error('提交失败:', error);
            alert('提交失败,请检查输入或重试');
        });
    }

    // 用useEffect监听PostDone变化,触发跳转
    useEffect(() => {
        if (PostDone) {
            window.location.assign('/AllBlog');
        }
    }, [PostDone]);

    return (
        <section className='Post-blog'>
            <h1 className='post-header-text'> Post what you Like</h1>
            <div className='form-post'>
                <label>
                    <h3>title</h3>
                    <input type="text" className='title-from' onChange={(e) => setTitle(e.target.value)}/>
                </label>
                <label>
                    <h3>Pergraph</h3>
                    <textarea type="text" className='p-from' rows="6" onChange={(e) => setBody(e.target.value)}></textarea>
                </label>
                <button className='btn una' onClick={handelPost}>Post</button>
            </div>
        </section>
    )
}

export default PostBlog

额外说明

  • 新增的catch回调可以帮你排查请求失败的原因,比如后端接口错误、跨域问题等。
  • 直接在组件函数体中写{PostDone ? window.location.assign('/AllBlog'): null}的写法不规范,每次组件渲染都会执行这个表达式,可能导致不必要的重复执行,用useEffect可以避免这个问题。

内容的提问来源于stack exchange,提问作者Amar Ahmed

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.02 01:31:17