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

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

问题描述

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

如果我执行诸如 http://localhost:3000/movies/1 之类的操作,则删除有效,显示它应该删除什么 id,但是有什么方法可以设置它?要删除连接到我单击的按钮的列表?类似于 http://localhost:3000/movies/"id"?我将不胜感激任何帮助,因为我完全不知道如何继续下去

从'react'导入React;从 'react-dom' 导入 ReactDom;从 'axios' 导入 axios;从./list.jsx"导入列表;class Form 扩展 React.Component {构造函数(道具){超级(道具)this.state = {名称:'',类型:'',描述:'',ID:'',电影: [],}}handleChangeOne = e =>{this.setState({名称:e.target.value})}handleChangeTwo = e =>{this.setState({类型:e.target.value})}handleChangeThree = e =>{this.setState({描述:e.target.value})}handleSubmit = e =>{e.preventDefault()const url = `http://localhost:3000/movies/`;axios.post(网址,{名称:this.state.name,类型:this.state.type,描述:this.state.description,id:this.state.id}).then(res => {//console.log(res);//console.log(res.data);this.setState({电影:[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 => {控制台日志(res.data);}).catch((错误) => {控制台日志(错误);})}//editMovie = e =>{//const url = `http://localhost:3000/movies/`;//e.preventDefault();//const id = e.target.data("id");//axios.put(url + id, {//名称: this.state.name,//类型:this.state.type,//描述:this.state.description,//})//.then(res => {//console.log(res.data);//})//.catch((err) => {//console.log(err);//})//}使成为() {返回 (<form onSubmit={this.handleSubmit}><input type="text" placeholder="movie" onChange={this.handleChangeOne}/><input type="text" placeholder="电影类型" onChange={this.handleChangeTwo}/><textarea cols={40} rows={5} placeholder="description of the movie" onChange={this.handleChangeThree}></textarea><input type="submit" value="添加电影"></input><List removeClick={this.handleRemove} editClick={this.editMovie}/></表单>)}}导出默认表单

列表:

从'react'导入React;从 'react-dom' 导入 ReactDom;从 'axios' 导入 axios;类列表扩展了 React.Component{构造函数(道具){超级(道具)this.state = {电影: [],}}componentDidMount() {const url = `http://localhost:3000/movies`;控制台日志(网址);axios.get(url).then(res => {控制台日志(res.data);const 电影 = res.data;this.setState({电影:电影})}).catch((错误) => {控制台日志(错误);})}//editMovie =(e) =>{//console.log("它适用于编辑!");//if (typeof this.props.editClick === "function") {//this.props.editClick(e)//    } 别的 {//console.log("不适用于编辑");//}//}removeMovie =(e) =>{console.log("它适用于删除!");if (typeof this.props.removeClick === "function") {this.props.removeClick(e)} 别的 {console.log("不适用于删除");}}使成为(){让电影 = this.state.movi​​es.map(e =><ul onClick={this.editMovie}><li data-id={e.id}>{e.name}<li data-id={e.id}>{e.type}<li data-id={e.id}>{e.描述}<button type="submit" onClick={this.removeMovie}>删除</button></ul>)返回(<div>{电影}

)}}导出默认列表;

Json 部分

<代码>{电影": [{身份证":1,"name": "Kongi","类型": "戏剧",描述":关于猴子的电影"},{身份证":2,"name": "寂静岭",类型":惊悚",描述":关于怪物的电影"},{"name": "哈利波特","类型": "幻想","description": "关于魔法与荣耀的电影",身份证":3}]}

解决方案

您可以将 movie 对象传递给 List 中的 removeMovie 函数> 组件并将其传递给 this.props.removeClick 函数.然后,您可以将 movieid 用于您的请求,如果 DELETE 请求成功,则从 state 中删除 movie.

示例

class Form extends React.Component {handleRemove = 电影 =>{const url = `http://localhost:3000/movies/${movie.id}`;公理.删除(网址).then(res => {this.setState(previousState => {返回 {电影:previousState.movi​​es.filter(m => m.id !== movie.id)};});}).catch(错误 => {控制台日志(错误);});};//...}类列表扩展了 React.Component {removeMovie = (e, 电影) =>{e.preventDefault();如果(this.props.removeClick){this.props.removeClick(电影);}};//...使成为() {返回 (<div>{this.state.movi​​es.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, 电影)}>删除))}

);}}

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,

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

List:

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 part

{
  "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
    }
  ]
}

解决方案

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.

Example

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天全站免登陆