javascript 为什么数据没有显示

rxztt3cl  于 2023-02-11  发布在  Java
关注(0)|答案(2)|浏览(150)

当我添加location.assign('AllBlog')时,它不会发布数据,但如果我删除它,它会工作。

import React, { useState } 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
            })
            setPostDone(()=>true)
    }

    {PostDone ? window.location.assign('/AllBlog'): null}

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>
            {/* <label>
                <h3>Upload Image</h3>
                <input type="file"/>
            </label> */}

            <button className='btn una' onClick={()=>handelPost()}>Post</button>
            </div>

        </section>
    )
}

export default PostBlog
wbrvyc0a

wbrvyc0a1#

看起来问题出在你尝试在一个成功的帖子后将用户重定向到“AllBlog”页面的方式上。正确的方法是使用react-router-dom库中的useHistory钩子来编程地将用户导航到另一个页面。
下面是代码的更新版本,其中包含了一些更改:

import React, { useState } from 'react'
import './PostBlog.css'
import axios from 'axios'
import { useNavigate } from 'react-router-dom'

function PostBlog() {
  const navigate = useNavigate()
  const [title, setTitle] = useState(null)
  const [body, setBody] = useState(null)

  const handlePost = () => {
    axios.post('http://127.0.0.1:7000/postBlog', {
      title: title,
      body: body
    })
      .then(() => {
        setTitle(null)
        setBody(null)
        navigate('/AllBlog')
      })
  }

  return (
    <section>
      <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={handlePost}>Post</button>
      </div>
    </section>
  )
}

export default PostBlog
vfh0ocws

vfh0ocws2#

函数axios.post是异步的。因此,window.location.assign可能在请求完成之前执行。要解决此问题,请使函数handelPost异步,并将await添加到axios.post。

const handelPost = async () => {
  await axios.post('http://127.0.0.1:7000/postBlog', {
    title:title,
    body:body
  });

  setPostDone(() => true);
}

相关问题