繁体   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