axios 删除按钮在服务器上工作,但不更新UI屏幕

wkftcu5l  于 11个月前  发布在  iOS
关注(0)|答案(3)|浏览(120)

我在服务器db.json上的数据对象运行在端口3001/person上,我设计了删除按钮,当点击时应该删除特定对象。但是当我点击删除时,它从db.json服务器上删除,但UI部分不会更新,直到我刷新页面。
App.js

import { useState, useEffect } from 'react';
import personService from './services/person'

function App() {
  const [persons, setPersons] = useState([
    // { name: 'Arto Hellas', number: '00000000', id: 1 },
  ]);

  const [newName, setNewName] = useState('');
  const [newNum, setNewNum] = useState('');
  const [searchTerm, setSearchTerm] = useState('');

  const handleNameInput = (e) => {
    setNewName(e.target.value);
  };

  const handleNumberInput = (e) => {
    setNewNum(e.target.value);
  };

  const handleSearchTerm = (e) => {
    setSearchTerm(e.target.value);
  };

  const addName = (e) => {
    e.preventDefault();
    if (persons.some((person) => person.name === newName)) {
      alert(`${newName} already exists`);
      return;
    }
    const nameObject = {
      name: newName,
      number: newNum,
      id: persons.length + 1,
    };
    personService.create(nameObject).then(response => {
      setPersons(persons.concat(response.data));
      setNewName('');
      setNewNum('');
    })
  };

  useEffect(() => {
    personService.getAll().then(response => {
      setPersons(response.data)
    })
  }, [])

  const filteredPersons = persons.filter((person) =>
    person.name.toLowerCase().includes(searchTerm.toLowerCase())
  );

  const deletePerson = (id) => {
    const personn = { ...persons }
    
    personService.deletee(id, personn)
      .then(response => {
        console.log('deleted', id)
      })
      .catch((err) => {
        alert("ERROR", err)
      })
  }

  return (
    <div>
      <h1>PHONEBOOK</h1>
      <div>
        Filter shown with: 
        <input onChange={handleSearchTerm} value={searchTerm} />
      </div>
      <form>
        <div>
          <h2>ADD</h2>
          <div>
            name: <input onChange={handleNameInput} value={newName} />
          </div>
          <div>
            number: <input onChange={handleNumberInput} value={newNum} />
          </div>
        </div>
        <button type="submit" onClick={addName}>
          add
        </button>
      </form>
      <h2>Numbers</h2>
      <ul>
        {filteredPersons.map((person) => (
          <li key={person.id}>
            {person.name} {person.number} 
            <button onClick={() => deletePerson(person.id)}>Delete</button>
          </li>
        ))}
      </ul>
    </div>
  );
}

export default App;

字符串

t30tvxxf

t30tvxxf1#

您需要重新获取数据:

import { useState,useEffect } from 'react';
import personService from './services/person'

function App() {
  const [persons, setPersons] = useState([
    // { name: 'Arto Hellas', number: '00000000', id: 1 },
  ]);

  const [newName, setNewName] = useState('');
  const [newNum, setNewNum] = useState('');
  const [searchTerm, setSearchTerm] = useState('');

  const handleNameInput = (e) => {
    setNewName(e.target.value);
  };

  const handleNumberInput = (e) => {
    setNewNum(e.target.value);
  };

  const handleSearchTerm = (e) => {
    setSearchTerm(e.target.value);
  };

  const addName = (e) => {
    e.preventDefault();
    if (persons.some((person) => person.name === newName)) {
      alert(`${newName} already exists`);
      return;
    }
    const nameObject = {
      name: newName,
      number: newNum,
      id: persons.length + 1,
    };
    personService.create(nameObject).then(response=>{
        setPersons(persons.concat(response.data));
    setNewName('');
    setNewNum('');
    })
    
  };

const getPersonService =()=> {
 personService.getAll().then(response=>{
      setPersons(response.data)
  })
}

  useEffect(()=>{
    getPersonService();
  },[])

  const filteredPersons = persons.filter((person) =>
    person.name.toLowerCase().includes(searchTerm.toLowerCase())
  );

  const deletePerson=(id)=>{
    const personn={...persons}
    
    personService.deletee(id,personn).then(response=>{
      console.log('deleted',id)
      getPersonService();
    }).catch((err)=>{
      alert("ERROR",err)
      
    })
  }

  return (
    <div>
      <h1>PHONEBOOK</h1>
      <div>
        Filter shown with: <input onChange={handleSearchTerm} value={searchTerm} />
      </div>
      <form>
        <div>
          <h2>ADD</h2>
          <div>
            name: <input onChange={handleNameInput} value={newName} />
          </div>
          <div>
            number: <input onChange={handleNumberInput} value={newNum} />
          </div>
        </div>
        <button type="submit" onClick={addName}>
          add
        </button>
      </form>
      <h2>Numbers</h2>
      <ul>
        {filteredPersons.map((person) => (
          <li key={person.id}>
            {person.name} {person.number} <button onClick={()=>deletePerson(person.id)}>Delete</button>
          </li>
        ))}
      </ul>
    </div>
  );
}

export default App;

字符串

omhiaaxx

omhiaaxx2#

当你使用delete API删除一个项目时,它只会更新服务器的数据库。为了在UI中反映这个变化,你需要发出一个额外的GET请求来从服务器获取更新的数据,然后更新你的React应用程序中的状态。这可以确保UI与服务器数据保持同步,而不需要刷新整个页面。

const getData =()=> {
 personService.getAll().then(response=>{
      setPersons(response.data)
  })
}

  useEffect(()=>{
    getData();
  },[])

  const filteredPersons = persons.filter((person) =>
    person.name.toLowerCase().includes(searchTerm.toLowerCase())
  );

  const deletePerson=(id)=>{
    const personn={...persons}
    personService.deletee(id,personn).then(response=>{
      console.log('deleted',id)
      getData();
    }).catch((err)=>{
      alert("ERROR",err)
      
    })
  }

字符串

0wi1tuuw

0wi1tuuw3#

问题

当您调用服务代码来删除一个人时,这显然只会对后端数据库进行更改。App组件的persons状态保持不变。当您重新加载页面时,useEffect钩子再次运行并从DB中获取所有人数据。

解决方案

类似于addName回调处理程序进行API/服务调用 * 然后 * 排队状态更新以将新数据添加到persons状态的方式:

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

  if (persons.some((person) => person.name === newName)) {
    alert(`${newName} already exists`);
    return;
  }

  const nameObject = {
    name: newName,
    number: newNum,
    id: persons.length + 1,
  };

  personService.create(nameObject)
    .then(response => {
      // Creation success, add to local state
      setPersons(persons => persons.concat(response.data));

      setNewName('');
      setNewNum('');
    });
};

字符串
同样,deletePerson回调处理程序也应该将一个状态更新排入persons状态队列,以通过传递的id值删除(例如过滤)person对象。

const deletePerson = (id) => {
  personService.deletee(id, persons.slice())
    .then(response => {
      // Delete success, remove from local state
      setPersons(persons => persons.filter(person => person.id !== id));
    }).catch((err) => {
      alert("ERROR", err);
    });
};

相关问题