如果我用照片编辑我的数据,并且如果我没有选择任何照片并按提交按钮,则照片字段在使用 axios 的 React context api 中会变为空

问题描述 投票:0回答:2
I am very tried to solved it. I try every possible way but it behavior like when i edit text data and do not touch image, image part will be empty. but if i only update without touching my data its remaining same.This behavior is strange to me. plz help

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 part:  


  #here my context file
  
  import { createContext } from "react";
  
  const NoteContext = createContext();
  
  
  export default NoteContext;
  
  
  #here in my noteState file 
  
  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);
          })
      }
  
      // update note
  
      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);
          })
      }
  
  # update laravel api in controller
  
  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']);
      }
reactjs laravel edit
2个回答
0
投票

这里 const all_data 下面的代码应该是这样的:

        name:obj_data.name,
        email:obj_data.email,
        phone:obj_data.phone,
        description:obj_data.description,
        photo:obj_data.photo,
        old_photo:obj_data.old_photo
        
    });    ```


0
投票

问题是即使不需要,您的方法也会更新照片。我建议你这样做:

public function update(Request $request,$id){
    $update = Admin::find($id);
    ... // other things you want to do
    if ($request->hasFile('photo')){
        $image = $request->file('photo');
        $unique_name = hexdec(uniqid()).'.'.$image->getClientOriginalExtension();
        Image::make($image)->resize(500,300)->save('images/'.$unique_name);
        $update->photo = $unique_name;
    }
    ... // other things you want to do
    $update->update();
    return response()->json(['success'=>'successful']);
}

其中如果提交了照片,则更新照片,否则不更新。

© www.soinside.com 2019 - 2024. All rights reserved.