使用axios删除请求-React

时间:2018-07-16 20:21:20

标签: javascript json reactjs axios

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

如果我做类似http://www.chartjs.org/docs/latest/configuration/animations.html的操作,删除它可以显示应该删除的ID,但是有什么方法可以设置它吗?要删除与我单击的按钮相关的列表?像http://localhost:3000/movies/1“ 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
    }
  ]
}

2 个答案:

答案 0 :(得分:0)

您可以将movie对象传递给removeMovie组件中的List函数,并将其传递给this.props.removeClick函数。然后,您可以将id中的movie用于您的请求,如果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>
    );
  }
}

答案 1 :(得分:0)

一个使用钩子的简单例子:

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