首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
MCP广场
社区首页 >问答首页 >包含抛出"TypeError: Cannot read property 'onSubmit‘of undefined“的按钮的映射数据

包含抛出"TypeError: Cannot read property 'onSubmit‘of undefined“的按钮的映射数据
EN

Stack Overflow用户
提问于 2020-01-13 19:20:50
回答 1查看 43关注 0票数 1

我正在编写一个全栈应用程序,它显示来自我的sql服务器的问题,并显示在前端。在每个问题中都有一个接受和拒绝按钮。我只想让我的accept向我的数据库发送一个响应,并拒绝向我的数据库发送一个响应(当然两者是不同的)。

但是,当创建问题并创建绑定到处理提交的提交时,它会抛出一个错误(如下所示)。

我如何为每个答案创建两个单独的句柄提交,然后将数据发送到另一个表,但使用映射问题上的ID,以便它可以用作外键。

这是因为它是映射数据吗?

有问题的代码

代码语言:javascript
运行
复制
import React, { Component } from "react";
import "./customers.css";
import { Link } from "react-router-dom";

class DisplayUsers extends React.Component {
  constructor() {
    super();

    this.state = { questions: [], QuestionsAnswer: [], QuestionsSeverity: [] };
    this.onSubmit = this.handleSubmit.bind(this);
  }
  componentDidMount() {
    this.setState({
      questions: this.getItems()
    });
  }

  getItems() {
    fetch("/user-questions")
      .then(recordset => recordset.json())
      .then(results => {
        console.log(results.recordset);
        this.setState({ questions: results.recordset });
      });
  }

  handleSubmit(e) {
    e.preventDefault();
    const data = {
      QuestionsAnswer: this.state.QuestionsAnswer,
      QuestionsSeverity: this.state.QuestionsSeverity
    };

    fetch("/Question-Response", {
      method: "POST", // or 'PUT'
      headers: {
        Accept: "application/json, text/plain, */*",
        "Content-Type": "application/json"
      },
      body: JSON.stringify(data)
    })
      .then(response => response.json())
      .then(data => {
        console.log("Success:", data);
      })
      .catch(error => {
        console.error("Error:", error);
      });
  }

  render() {
    console.log(this.state.questions);
    return (
      <ul>
        {this.state.questions &&
          this.state.questions.map(function(question, index) {
            return (
              <div className="jumbotron">
                <li> Question ID: {question.QuestionId}</li>
                <li> Question:{question.Question}</li>
                <li>
                  <button onClick={this.onSubmit}>Accepted</button> 
                  <button>Declined</button>
                </li>

                <li>
                  <textarea
                    onChange={e =>
                      this.setState({ QuestionsAnswer: e.target.value })
                    }
                    rows="4"
                    cols="160"
                    id="TITLE"
                  ></textarea>
                </li>
              </div>
            );
          })}
      </ul>
    );
  }
}

export default DisplayUsers;

错误

代码语言:javascript
运行
复制
Uncaught (in promise) TypeError: Cannot read property 'onSubmit' of undefined
    at DisplayQuestions.js:62
    at Array.map (<anonymous>)
    at DisplayUsers.render (DisplayQuestions.js:54)
    at finishClassComponent (react-dom.development.js:18470)
    at updateClassComponent (react-dom.development.js:18423)
    at beginWork$1 (react-dom.development.js:20186)
    at HTMLUnknownElement.callCallback (react-dom.development.js:336)
    at Object.invokeGuardedCallbackDev (react-dom.development.js:385)
    at invokeGuardedCallback (react-dom.development.js:440)
    at beginWork$$1 (react-dom.development.js:25780)
    at performUnitOfWork (react-dom.development.js:24695)
    at workLoopSync (react-dom.development.js:24671)
    at performSyncWorkOnRoot (react-dom.development.js:24270)
    at react-dom.development.js:12199
    at unstable_runWithPriority (scheduler.development.js:697)
    at runWithPriority$2 (react-dom.development.js:12149)
    at flushSyncCallbackQueueImpl (react-dom.development.js:12194)
    at flushSyncCallbackQueue (react-dom.development.js:12182)
    at scheduleUpdateOnFiber (react-dom.development.js:23709)
    at Object.enqueueSetState (react-dom.development.js:13994)
    at DisplayUsers.push../node_modules/react/cjs/react.development.js.Component.setState (react.development.js:325)
    at DisplayQuestions.js:23
EN

回答 1

Stack Overflow用户

发布于 2020-01-13 19:38:29

作用域问题。

在render函数中,将var self = this;添加到console.log(this.state.questions);之上,然后使用self.onSubmit

您处于this.state.questions.map的回调函数的作用域内,因此this不会引用该组件。

代码语言:javascript
运行
复制
  render() {
    var self = this;
    console.log(this.state.questions);
    return (
      <ul>
        {this.state.questions &&
          this.state.questions.map(function mapFn(question, index) {
              ...
                  // this === scope of mapFn ↑ which is undefined
                  // self === scope of render function
                  <button onClick={self.onSubmit}>Accepted</button> 
      ....
      </ul>
    );
  }

编辑

另一种可能更好的映射方法是将作用域传递给函数

代码语言:javascript
运行
复制
this.state.questions.map(function(question, index) {
    // this === scope of render function
}, this)
票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/59715629

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档