反应TypeError:this.setState不是函数

时间:2019-09-16 10:01:44

标签: javascript reactjs

目前,我正在编写一个可与​​.NET Core Web API配合使用的应用程序,并且得到:

TypeError: this.setState is not a function

我将在最后一段中确切解释何时出现此错误

现在,该视图旨在按以下方式工作,在页面上,我有一个表,该表中的数据来自JSON数据数组,并在其旁边输入了几个输入。当我单击表格行时,它将把行数据放入输入中,我可以从此处编辑数据。处理此问题的方法有两个,首先是:editData向api发送POST请求,然后修改数据库中的已编辑对象。完成此请求后,第二个功能:getData将运行并用新的,已编辑的数据刷新表。这是它的外观:

构造函数:

class SomeClass extends React.Component {
    constructor(props) {
        super(props);
        this.props = props;
        this.state = {
            someArray: [],
            tableData1: "",
            tableData2: "",

            validationSummary: [],
            isSubmitting: false
        }
        this.handleChange = this.handleChange.bind(this); //function to handle change on inputs
        this.getData = this.getData.bind(this);
        this.editData= this.editData.bind(this);
    }

获取数据的功能:

    async getData() {
        return fetch("http://localhost:5000/api/somecontroller/getroute")
            .then(response => response.json())
            .then(data => {
                this.setState({
                    someArray: data,
                    tableData1: "",
                    tableData2: "", //clear inputs
                })
            })
    }

最后编辑对象功能:

    async editData() {
        var validationSummary = []

        if (this.state.tableData1 !== "" && this.state.tableData2 !== "") {
            this.setState = {
                validationSummary: [], //clear summary
                isSubmitting: true
            }

            let response = await fetch('http://localhost:5000/api/somecontroller/editroute', {
                method: "POST",
                headers: {
                    'Content-Type': 'application/json'
                },
                body: JSON.stringify({
                    data1: tableData1,
                    data2: tableData2
                })
            });

            if (response.status !== 200) {
                validationSummary.push("Something went wrong")
                this.setState = {
                    validationSummary: validationSummary,
                    isSubmitting: false
                }
            }

            else {
                await this.getData()
            }
        }

        else {
            validationSummary.push("Inputs cannot be empty")
            this.setState = {
                validationSummary: validationSummary,
                isSubmitting: false
            }
        }
    }

问题在于,每当我编辑一些数据并将其提交以发送请求至API时,网站都会停止运行,并且在this.setState函数的getData行上出现上述错误:

    async getData() {
        return fetch("http://localhost:5000/api/somecontroller/getroute")
            .then(response => response.json())
            .then(data => {
                this.setState({ //getting error here

我已经阅读了与此类似的其他几个问题,但是每次解决方案是将功能绑定到this中的constructor时。但是,正如您在我的代码中看到的那样,我已经将getDataeditData函数绑定到this。我可能不得不提到,当我从this.setState函数中删除所有editData引用时,页面运行正常,并且不再出现任何错误。我是个新手,所以很好奇我为什么会收到此错误,以及如何在不从this.setState函数中删除editData引用的情况下解决此问题,因为我需要它们用于显示错误消息。

更新

amrs-tech的答案解决了我的问题,在editData中,将this.setState = {...}更改为this.setState({...})使其可行。希望将来对某人有用!

4 个答案:

答案 0 :(得分:1)

if (this.setState.tableData1 !== "" && this.setState.tableData2 !== "")

这是不正确的。应该是这样的:

if (this.state.tableData1 !== "" && this.state.tableData2 !== "")

答案 1 :(得分:0)

您的editData应该像:

async editData() {
        var validationSummary = []

        if (this.state.tableData1 !== "" && this.state.tableData2 !== "") {
            this.setState ({
                validationSummary: [], //clear summary
                isSubmitting: true
            })

            let response = await fetch('http://localhost:5000/api/somecontroller/editroute', {
                method: "POST",
                headers: {
                    'Content-Type': 'application/json'
                },
                body: JSON.stringify({
                    data1: tableData1,
                    data2: tableData2
                })
            });

            if (response.status !== 200) {
                validationSummary.push("Something went wrong")
                this.setState ({
                    validationSummary: validationSummary,
                    isSubmitting: false
                })
            }

            else {
                await this.getData()
            }
        }

        else {
            validationSummary.push("Inputs cannot be empty")
            this.setState ({
                validationSummary: validationSummary,
                isSubmitting: false
            })
        }
    }

希望它能起作用。您可以参考有关React 状态和生命周期-here

的一些详细信息

答案 2 :(得分:0)

setState is a function,也是state and props are immutable

// this.state.tableData1
this.setState.tableData1

// this.setState({...})
// and either way its should considered immutable
this.setState = {
  validationSummary: [], //clear summary
  isSubmitting: true
};

// also this is redundant because props are immutable.
this.props = props;

答案 3 :(得分:0)

解决此问题的另一种快速方法是将“ this”保留为变量

async getData() {
var scope = this;
        return fetch("http://localhost:5000/api/somecontroller/getroute")
            .then(response => response.json())
            .then(data => {
                scope.setState({ // scope replace 'this' here