簡體   English   中英

使用 axios 刪除請求 - React

[英]Delete request with axios - React

我正在嘗試創建基於 Json 服務器包的小應用程序,這將幫助我記住我有空時想看的電影,想學習 React 和 Axios,所以我正在使用這些技術做這件事,想法是當我點擊添加電影按鈕 - 電影將被添加到 Json 數據庫,點擊刪除 - 特定電影將被刪除,點擊列表時 - 我將能夠編輯文本,

如果我執行諸如http://localhost:3000/movies/1 之類的操作,Delete 就可以工作,以顯示它應該刪除的 id,但是有沒有辦法設置它? 要刪除連接到我單擊的按鈕的列表? 類似於http://localhost:3000/movies/ “id”? 我將不勝感激任何幫助,因為我完全不知道如何繼續

import React from 'react';
import ReactDom from 'react-dom';
import axios from 'axios';
import List from "./list.jsx";

class Form extends React.Component {
    constructor(props) {
        super(props)
        this.state = {
            name:'',
            type:'',
            description:'',
            id:'',
            movies: [],

        }
    }

    handleChangeOne = e => {
        this.setState({
            name:e.target.value
        })
    }
    handleChangeTwo = e => {
        this.setState({
            type:e.target.value
        })
    }
    handleChangeThree = e => {
        this.setState({
            description:e.target.value
        })
    }

    handleSubmit = e => {
        e.preventDefault()
        const url = `http://localhost:3000/movies/`;
        axios.post(url, {
            name: this.state.name,
            type: this.state.type,
            description:this.state.description,
            id:this.state.id
        })
            .then(res => {
                // console.log(res);
                // console.log(res.data);
                this.setState({
                    movies:[this.state.name,this.state.type,this.state.description, this.state.id]
                })
            })
    }

    handleRemove = (e) => {
        const id = this.state.id;
        const url = `http://localhost:3000/movies/`;
        // const id = document.querySelectorAll("li").props['data-id'];
        e.preventDefault();
        axios.delete(url + id)
            .then(res => {
                console.log(res.data);
            })
            .catch((err) => {
                console.log(err);
            })
    }

    // editMovie = e => {
    //     const url = `http://localhost:3000/movies/`;
    //     e.preventDefault();
    //     const id = e.target.data("id");
    //     axios.put(url + id, {
    //             name: this.state.name,
    //             type: this.state.type,
    //             description:this.state.description,
    //     })
    //         .then(res => {
    //             console.log(res.data);
    //         })
    //         .catch((err) => {
    //             console.log(err);
    //         })
    // }


    render() {
        return (

            <form onSubmit={this.handleSubmit}>
                <input type="text" placeholder="movie" onChange={this.handleChangeOne}/>
                <input type="text" placeholder="type of movie" onChange={this.handleChangeTwo}/>
                <textarea cols={40} rows={5} placeholder="description of the movie" onChange={this.handleChangeThree}></textarea>
                <input type="submit" value="Add movie"></input>
                <List removeClick={this.handleRemove} editClick={this.editMovie}/>
            </form>
        )
    }
}

export default Form

列表:

import React from 'react';
import ReactDom from 'react-dom';
import axios from 'axios';


class List extends React.Component{
    constructor(props){
        super(props)
        this.state = {
            movies: [],

        }
    }

    componentDidMount() {
        const url = `http://localhost:3000/movies`;
        console.log(url);
        axios.get(url)
            .then(res => {
                console.log(res.data);
                const movies = res.data;
                this.setState({
                    movies: movies
                })
            })
            .catch((err) => {
                console.log(err);
            })

    }

    // editMovie =(e) => {
    //     console.log("it works with edit!");
    //     if (typeof this.props.editClick === "function") {
    //         this.props.editClick(e)
    //     } else {
    //         console.log("Doesn't work with edit");
    //     }
    // }

    removeMovie =(e) => {
        console.log("it works with remove!");
        if (typeof this.props.removeClick === "function") {
            this.props.removeClick(e)
        } else {
            console.log("Doesn't work with remove");
        }
    }


    render(){
        let movies = this.state.movies.map(e =>
            <ul onClick={this.editMovie}>
                <li data-id={e.id}>
                    {e.name}
                </li>
                <li data-id={e.id}>
                    {e.type}
                </li>
                <li data-id={e.id}>
                    {e.description}
                </li>
                <button type="submit" onClick={this.removeMovie}>Delete</button>
            </ul>)

        return(
            <div>
                {movies}
            </div>
        )
    }
}

export default List;

Json 部分

{
  "movies": [
    {
      "id": 1,
      "name": "Kongi",
      "type": "drama",
      "description": "movie about monkey"
    },
    {
      "id": 2,
      "name": "Silent Hill",
      "type": "thriller",
      "description": "movie about monsters"
    },
    {
      "name": "Harry potter",
      "type": "fantasy",
      "description": "movie about magic and glory",
      "id": 3
    }
  ]
}

您可以將movie對象傳遞給List組件中的removeMovie函數,並將其傳遞給this.props.removeClick函數。 然后,您可以將movieid用於您的請求,如果 DELETE 請求成功,則從狀態中刪除movie

例子

class Form extends React.Component {
  handleRemove = movie => {
    const url = `http://localhost:3000/movies/${movie.id}`;

    axios
      .delete(url)
      .then(res => {
        this.setState(previousState => {
          return {
            movies: previousState.movies.filter(m => m.id !== movie.id)
          };
        });
      })
      .catch(err => {
        console.log(err);
      });
  };

  // ...
}

class List extends React.Component {
  removeMovie = (e, movie) => {
    e.preventDefault();

    if (this.props.removeClick) {
      this.props.removeClick(movie);
    }
  };

  // ...

  render() {
    return (
      <div>
        {this.state.movies.map(movie => (
          <ul onClick={this.editMovie}>
            <li data-id={movie.id}>{movie.name}</li>
            <li data-id={movie.id}>{movie.type}</li>
            <li data-id={movie.id}>{movie.description}</li>
            <button type="submit" onClick={e => this.removeMovie(e, movie)}>
              Delete
            </button>
          </ul>
        ))}
      </div>
    );
  }
}

使用鈎子的簡單示例:

const URL = 'https://jsonplaceholder.typicode.com/users'

const Table = () => {
    const [employees, setEmployees] = React.useState([])

    React.useEffect(() => {
        getData()
    }, [])

    const getData = async () => {

        const response = await axios.get(URL)
        setEmployees(response.data)
    }

    const removeData = (id) => {

        axios.delete(`${URL}/${id}`).then(res => {
            const del = employees.filter(employee => id !== employee.id)
            setEmployees(del)
        })
    }

    const renderHeader = () => {
        let headerElement = ['id', 'name', 'email', 'phone', 'operation']

        return headerElement.map((key, index) => {
            return <th key={index}>{key.toUpperCase()}</th>
        })
    }

    const renderBody = () => {
        return employees && employees.map(({ id, name, email, phone }) => {
            return (
                <tr key={id}>
                    <td>{id}</td>
                    <td>{name}</td>
                    <td>{email}</td>
                    <td>{phone}</td>
                    <td className='opration'>
                        <button className='button' onClick={() => removeData(id)}>Delete</button>
                    </td>
                </tr>
            )
        })
    }

    return (
        <>
            <h1 id='title'>React Table</h1>
            <table id='employee'>
                <thead>
                    <tr>{renderHeader()}</tr>
                </thead>
                <tbody>
                    {renderBody()}
                </tbody>
            </table>
        </>
    )
}


ReactDOM.render(<Table />, document.getElementById('root'));

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM