小编Shu*_*Raj的帖子

如何在 axios post in React 后停止组件刷新。从 formData 上传图像后

我正在构建一个博客生成器,我需要在 onChange 事件中选择图像时上传图像,并且上传图像的 url 需要在状态中更新。

在发布图像上传请求后。组件会自动刷新,所选文件和状态也会刷新。

如何阻止组件刷新和 setState 来更新图像的正确 url..

handleChange = async (event) =>
{
    event.preventDefault();
    if(event.target.name == 'file')
    {


        var x=event.target.files[0]
        var y= event.target.name
        let formData = new FormData();
        formData.append('file',x)
        const response = await axios.post('http://localhost:8009/post/image',formData,{
           headers: {
             'Content-Type': 'multipart/form-data'
          }
        })
        let {data} = await response
        console.log(data)
        let file1 = data.name
        this.setState({
            content:{
                key:uuid(),
                name:y,
                file:file1,
                content:URL.createObjectURL(x)
            }
        })

   }
}
Run Code Online (Sandbox Code Playgroud)

图像的形式如下:

<input type="file" name="file" className="form-control-file"  onChange={this.handleChange} required/>
Run Code Online (Sandbox Code Playgroud)

节点上的后端:

router.post('/image',(req,res)=>
{
    console.log(req)

    let file = req.files.file;
    filename = …
Run Code Online (Sandbox Code Playgroud)

multipartform-data node.js reactjs axios

5
推荐指数
1
解决办法
3959
查看次数

标签 统计

axios ×1

multipartform-data ×1

node.js ×1

reactjs ×1