如何在react/mysql应用程序中编辑任务?

zfycwa2u  于 2022-10-31  发布在  Mysql
关注(0)|答案(3)|浏览(155)

所以我正在做一个待办事项应用,但到目前为止,我只能创建一个任务,或删除它。现在我正在尝试做另一个功能,我可以编辑特定的任务,通过点击编辑按钮,然后它会改变任务到一个输入区,我可以编辑任务名称。有人能帮助我吗?它现在的外观如下所示。

我的代码如下:

import React, { Component } from 'react';
import axios from "axios";

export default class TaskInput extends Component {
    constructor(props) {
        super(props)

        this.state = {
            task: " ",
            allTasks: [],
            strikeThrough: {textDecoration:""}
        }
    }

    changeHandler = (event) => {
        console.log(event.target.value)
        this.setState({
            task: event.target.value,
        })
    }

    handleStrikethrough = (completed, id) => {
    //    !completed ? this.setState({strikeThrough:{textDecoration: "line-through"}})  : this.setState({strikeThrough:{textDecoration:""}})
            // if (!completed) {
            //     console.log("not completed", !completed)
            //     this.setState({strikeThrough:{textDecoration: "line-through"}});
            //     axios.put("/api/task", {
            //         completed: !completed
            //     }, id).then(response => console.log(response))
            // } else {
            //     this.setState({strikeThrough:{textDecoration:""}})
            //     axios.put("/api/task", {
            //         completed: !completed
            //     }, id).then(response => console.log(response))
            // }
    }

    handleDelete = (taskId) => {
        axios.delete("/api/task/" + taskId).then(data => {
            console.log("You deleted the task with an id of ", data)
        })
        window.location.reload();
    }

    handleTaskEdit = () => {
        console.log("edit button worked")
    }

    submitHandler = (event) => {
        event.preventDefault() //to prevent page refresh
        console.log()

        fetch("/api/task", {
            method: "POST",
            headers: {
                'Content-Type': 'application/json',
                'Accept': 'application/json'
            },
            body: JSON.stringify(this.state),

        })
            .then(res => res.json())
            .then(data => console.log(data))
            .catch(err => console.log(err))
        this.setState({
            task: ""
        })
        window.location.reload()
    }

    componentDidMount() {
        console.log("component did mount")

        const self = this;
        axios.get("/api/tasks").then(function (data) {
            self.setState({
                allTasks: data.data
            })
            // console.log(self.state.allTasks[0].task)
        })
    }

    render() {
        const {strikeThrough, task, allTasks} = this.state; //destructuring the state
        return (
            <div>
                <form onSubmit={this.submitHandler} >
                    <label style={{ margin: "5px 0px" }}>Create a Task:</label>
                    <input value={this.state.task} onChange={this.changeHandler} style={{ width: "100%" }}></input>
                    <input style={{ padding: "5px", marginTop: "5px" }} type="submit"></input>
                </form>
                <hr></hr>
                <br></br>
                <ul>
                    {this.state.allTasks.map(task => (
                        <li style={strikeThrough} onClick={()=>this.handleStrikethrough(task.completed, task.id)} className="tasks">{task.task}
                        <button onClick = {() => this.handleDelete(task.id)}>x</button>
                        <button onClick={this.handleTaskEdit}>edit</button>
                        </li>
                    )
                    )}
                </ul>
            </div>
        )
    }
}
uqjltbpv

uqjltbpv1#

您可以在其对应的“编辑”按钮上设置任务ID,然后在单击“编辑”按钮时使用ID获取任务并将该任务发送到编辑组件。

niknxzdl

niknxzdl2#

首先是handleTaskEdit,在这里您将任务名称设置为任务属性,并设置可编辑任务的ID:

handleTaskEdit = id =>
  this.setState({ task: this.state.allTasks.find(el => el.id === id).task })

其次,创建两个新方法createTask和updateTask:

createTask = () => {
        fetch("/api/task", {
            method: "POST",
            headers: {
                'Content-Type': 'application/json',
                'Accept': 'application/json'
            },
            body: JSON.stringify({task: this.state.task}),

        })
            .then(res => res.json())
            .then(data => this.setState({
              task: '', 
              allTasks: [...this.state.allTasks, data]}))
            .catch(err => console.log(err))
}
updateTask = () => {
    fetch("/api/task", {
        method: "PATCH",
        headers: {
            'Content-Type': 'application/json',
            'Accept': 'application/json'
        },
        body: JSON.stringify({task: this.state.task, id: this.state.editableTaskId}),

    })
        .then(res => res.json())
        .then(data => this.setState({
          task: '',
          editableTaskId: null,
          allTasks: this.state.allTasks.map(el => 
          el.id === data.id ? data : el)})) // Or take new name and id from state
        .catch(err => console.log(err))
}

最后,您需要更新submitHandler和handleDelete:

submitHandler = () => {
    if (this.state.editableTaskId) {
      this.updateTask();
    } else {
      this.createTask()
    }
}
handleDelete = (taskId) => {
    axios.delete("/api/task/" + taskId).then(data => {
      this.setState({allTasks: this.state.allTasks.filter(el =>
        el.id !== data.id
      )})
    })
}
jvlzgdj9

jvlzgdj93#

方法如下:
有一个名为editTaskID的状态变量,并将默认值保持为空。在编辑按钮上,设置handleTaskEdit的功能,使其将editTaskID设置为单击编辑按钮的特定任务ID。
在呈现任务列表项的Map函数中,添加一个条件,例如:

{this.state.allTasks.map(task =>
             (
               <li style={strikeThrough}
                 onClick={()=>this.handleStrikethrough(task.completed, task.id)} 
                 className="tasks">
                 {
                   this.editTaskID
                   ?<input 
                        value={this.state.editTaskName} 
                        /*supposing editTaskName to be state variable that stores 
                        the edit textfield content.*/ 
                        onChange={this.changeEditHandler} style={{ width: "80%" }}>
                    </input>
                  :task.task
                 }
               <button onClick = {() => this.handleDelete(task.id)}>x</button>
               <button onClick={this.handleTaskEdit}>edit</button>
              </li>
            )
           )
}

这将检查editTaskID在呈现时是否被设置为null。如果它为null,所有任务将以纯文本形式出现,否则将以文本框形式出现。您也可以在allTasks[editTaskID]的帮助下将值添加到编辑任务输入字段。
在编辑按钮的handleTaskEdit函数上,确保将allTasks[editTaskID]设置为值editTaskName,并将状态变量editTaskID设置为null。调用必要的后端端点,以反映数据库中的更改。
希望能帮上忙谢谢。

相关问题