【问题标题】:onDelete() method executes two times, What will be the issue?onDelete() 方法执行两次,会出现什么问题?
【发布时间】:2020-05-20 09:00:02
【问题描述】:
import React, { Component } from 'react'
import axios from 'axios';

class deleteTodo extends Component {


    onDelete(){
        console.log("delete")
        axios.post('http://localhost:4000/todos/delete/'+this.props.match.params.id)
            .then(res => console.log(res.data));

        this.props.history.push('/');

    }

    render() {
        return (
                <div>
                    {this.onDelete()}

                </div>


        )
    }
}

export default deleteTodo

【问题讨论】:

  • 为什么deleteTodo是一个组件而不是一个函数
  • @ShubhamKhatri 因为我想让它处理待办事项应用程序的删除操作。所以我做了组件。
  • 您可以使用按钮并在其上添加一个onClick。你不应该在渲染中使用异步代码

标签: reactjs react-redux react-router


【解决方案1】:

回答您的问题:render() 因各种原因被多次调用,详情请参阅https://reactjs.org/docs/react-component.html#render

您可以尝试使用componentDidMount() 进行删除请求,如果它应该在组件安装后立即执行一次。

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

class deleteTodo extends Component {


    componentDidMount(){
        console.log("delete")
        axios.post('http://localhost:4000/todos/delete/'+this.props.match.params.id)
            .then(res => console.log(res.data));

        this.props.history.push('/');

    }

    render() {
        return (
                <div></div>
        )
    }
}

export default deleteTodo

我仍然认为这是一种接近你想要的效果的非常奇怪的方式。

【讨论】:

  • 它与这个 omponentDidMount() 配合得很好。处理这个的好方法是什么???请详细说明,我是反应js的新手
  • Tbh 我很久没有使用 React js,所以我不是最好的回答者。但我的猜测是在其他地方处理 POST 请求是一个更好的选择。例如。在您添加 deleteTodo 组件以执行删除任务的部分中
猜你喜欢
  • 1970-01-01
  • 2020-01-24
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2010-10-13
  • 2011-12-01
  • 1970-01-01
相关资源
最近更新 更多