使用axios删除请求-React [英] Delete request with axios - React

查看:82
本文介绍了使用axios删除请求-React的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试创建一个基于Json服务器软件包的小型应用程序,这将有助于我记住空闲时间想看的电影,想学习React和Axios,所以我正在使用这些技术,Idea当我单击添加电影"按钮时-电影将被添加到Json数据库中, 单击删除时-特定电影将被删除 然后点击列表-我将能够编辑文本,

I'm trying to create small app based on Json server package which will help me to remember movies I want to watch when I have free time, want to learn React and Axios so I'm doing it with these technologies , Idea is when I click on add movie button - movie will be added to Json database, when click on delete - particular movie will be deleted and when click on the list - I will be able to edit text,

如果我执行 http://localhost:3000/movies/1 之类的操作,则删除有效显示应该删除的ID,但是有什么方法可以设置呢?要删除与我单击的按钮相关的列表?类似于 http://localhost:3000/movies/"id"?我将不胜感激,因为我完全不知道如何继续前进

Delete works if I do something like http://localhost:3000/movies/1, to show what id should it delete, but is there any way to set it? To delete the list connected to button I'm clicking at? something like http://localhost:3000/movies/"id"? I will be grateful for any help as I totally don't have any idea how to move on with it

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从状态中删除.

You could pass the movie object to the removeMovie function in your List component and pass that to the this.props.removeClick function. You could then take the id of the movie to use for your request, and remove the movie from state if the DELETE request is successful.

示例

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>
    );
  }
}

这篇关于使用axios删除请求-React的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆