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

React Context API+Axios编辑时未选新照片致photo字段为空求助

问题描述

在React项目中使用Context API结合Axios时遇到异常:当编辑文本数据但不选择新照片并提交表单时,photo字段会变为空;但如果不修改任何数据直接提交,photo字段则保持正常。

相关代码

Edit 组件

const Edit = () => {
    const {editNote, edit, updateNote, setEdit} = useContext(NoteContext)
    const { id } = useParams();

    useEffect(()=>{
        editNote(id)
    },[])

    console.log('me',edit.photo);

    const handleUpdateFormSubmit = (e) => {
        e.preventDefault();

        const formData = new FormData(e.target);
        const obj_data = Object.fromEntries(formData.entries());
        
        const all_data = ({
            name:obj_data.name,
            email:obj_data.email,
            phone:obj_data.phone,
            description:obj_data.description,
            photo:obj_data.photo?? edit.photo,
        });

        updateNote(id,all_data);
    }
  return (
    <>
    <div className="wrap">
        <div className="row d-flex justify-content-center">
            <div className="col-md-6">
                <div className="card">
                    <div className="card-header">
                        <h2>Add Note</h2>
                    </div>
                    <div className="card-header">
                        <form onSubmit={handleUpdateFormSubmit} action="" >
                            <div className="my-3">
                                <label htmlFor="">Name</label>
                                <input name='name' value={edit.name} onChange={(e)=>setEdit(e.target.value)} className='form-control' type="text" />
                            </div>
                            <div className="my-3">
                                <label htmlFor="">Email</label>
                                <input name='email' value={edit.email} onChange={(e)=>setEdit(e.target.value)} className='form-control' type="text" />
                            </div>
                            <div className="my-3">
                                <label htmlFor="">Phone</label>
                                <input name='phone' value={edit.phone} onChange={(e)=>setEdit(e.target.value)} className='form-control' type="text" />
                            </div>
                            <div className="my-3">
                                <label htmlFor="">Description</label>
                                <input name='description' value={edit.description} onChange={(e)=>setEdit(e.target.value)} className='form-control' type="text" />
                            </div>
                            <div className="my-3">
                                <label htmlFor="">Photo</label>
                                <input name='old_photo' value={edit.photo}  type="hidden" />
                                <input name='photo'  className='form-control-file' type="file" />
                            </div>
                            <div className="my-3">
                                <input className='btn btn-primary' type="submit" />
                            </div>
                        </form>
                    </div>
                </div>
            </div>
        </div>
    </div>
    </>
  )
}

Context 文件

import { createContext } from "react";

const NoteContext = createContext();

export default NoteContext;

NoteState 文件

const [edit, setEdit] = useState([]);

// 获取编辑数据
const editNote = async (id) => {
    await axios.put(`http://localhost:8000/api/edit/${id}`).then((res)=>{
        setEdit(res.data)
    }).catch(function(error){
        console.log(error.response);
    })
}

// 更新数据
const updateNote = async (id, all_data) => {
    await axios.post(`http://localhost:8000/api/update/${id}`, all_data, { headers:{ "Content-Type":"multipart/form-data" } }).then(()=>{
        window.location.href = '/';
    }).catch(function(error){
        console.log(error.response);
    })
}

Laravel 控制器更新接口

public function update(Request $request,$id){
    $update = Admin::find($id);

    if ($request->hasFile('photo')){
        $image = $request->file('photo');
        $unique_name = hexdec(uniqid()).'.'.$image->getClientOriginalExtension();
        Image::make($image)->resize(500,300)->save('images/'.$unique_name);

    }else{
        $unique_name = $request->old_photo;
    }

    $update->name = $request->name;
    $update->email = $request->email;
    $update->phone = $request->phone;
    $update->description = $request->description;
    $update->photo = $unique_name;
    $update->updated_at = Carbon::now();
    $update->update();

    return response()->json(['success'=>'successful']);
}

内容的提问来源于stack exchange,提问作者Shahnewaj Sajib

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.05 12:35:14