javascript - 如何修复reactjs中的 "failed to compile"?

标签 javascript reactjs

我一直在尝试制作一个reactjs网站,但显示编译失败。我收到的错误很少,其中很少有这些状态和函数未定义,解决方案是什么。我粘贴了下面的代码。 我的代码所做的是,您输入标题和描述,然后当我单击“保存”按钮时它会保存帖子。我尝试将 snippetDescription 绑定(bind)到保存函数,但一切都未定义。

import React, { Component, useState } from "react";
import { Link } from "react-router-dom";
import { Button } from "react-bootstrap";

handleRequest = async (postId) => {  //passed postId here
  const post = this.state;
  const request = {
    method: "POST",
    headers: {
      "Content-Type": "application/json"
    }
  };
  if (postId != null) {
    post["id"] = postId;
  }
  try {
    const response = await fetch("/api/updateposts", {
      ...request,
      body: JSON.stringify(this.state)
    });

    const data = await response.json();
    if (data.status === 200) {
      console.log("success", "post saved successfully!");
    } else {
      console.log(
        "danger",
        "An error has occured while updating the post. Please try again"
      );
    }
  } catch (ex) {
    console.error(ex.stack);
    console.log(
      "danger",
      "An error has occured while updating the post. Please try again"
    );
  }
};

handlePost = (postId) => {            //passed postId here
  if (postId == null) {
    return handleRequest("/api/savepost");
  }
  return handleRequest("/api/updatepost");
};
const analysis = (snippetDescription) => {   //passed snippetDescription
  fetch("/api/analyse", {
    method: "POST",
    body: JSON.stringify({
      snippetdesc: "snippetDescription"
    }),
    headers: {
      "Content-type": "application/json; charset=UTF-8"
    }
  })
    .then(response => response.json())
    .then(
      textdata => {
        this.setState({
          textdata: textdata.data,
          textlen: snippetDescription.split(" ").length
        });
      },
      error => {
        console.log(error);
      }
    );
};

export default class MainText extends Component {
  constructor(props) {
    super(props);
    this.state = {
      title: "",
      description: "",
      id: null,
      snippetDescription: "",
      textlen: 0
    };
  }

  render() {

    return (
      <>  
           <input
                type="text"
                id="titletext"
                placeholder="Enter title here"
                limit-to="64"
                className="inptxt"
                onChange={title => this.setState({ title })}
              ></input>
            <span class="itemcenter">              
              <Link to="/about">
                <Button
                  className="btn savebtn"
                  onClick={() => handlePost({ ...this.state })}
                >
                  Save <i className="fas fa-save" />
                </Button>
              </Link>
            </span>
            <textarea
              class="textareaclass"
              placeholder="Enter your text here"
              onChange={snippetDescription =>
                this.setState({ snippetDescription })
              }
            ></textarea>
     </>
     )}

这是我收到的错误消息

Failed to compile.

./src/component/Text.js
  Line 5:     'handleRequest' is not defined       no-undef
  Line 15:    'postId' is not defined              no-undef
  Line 16:   'postId' is not defined              no-undef
  Line 43:    'handlePost' is not defined          no-undef
  Line 44:    'postId' is not defined              no-undef
  Line 45:   'handleRequest' is not defined       no-undef
  Line 47:   'handleRequest' is not defined       no-undef
  Line 119:  'snippetDescription' is not defined  no-undef
  Line 287:  'handlePost' is not defined          no-undef

我的状态没有传递给函数吗?另外我的函数handleRequest和handlePost怎么也没有定义?

更新: 我已将所有代码(函数)移至 react 组件内,添加了 this.handlePost ,但它仍然显示相同的错误。


./src/component/mainText.js
  Line 31:    'postId' is not defined              no-undef
  Line 32:   'postId' is not defined              no-undef
  Line 59:    'postId' is not defined              no-undef
  Line 60:   'handleRequest' is not defined       no-undef
  Line 62:   'handleRequest' is not defined       no-undef
  Line 134:  'snippetDescription' is not defined  no-undef

新更新:

我现在已经编辑了函数,并将值传递给了我之前在上面的代码中没有传递的函数,所以现在我得到的唯一错误是handleRequest未定义。我应该在某处声明handleRequest吗?

Line 60:   'handleRequest' is not defined       no-undef
Line 62:   'handleRequest' is not defined       no-undef

Updae:我添加了 this.handlerequest.bind(this),因此它不再显示错误。我希望绑定(bind)是正确的。有人可以验证一下

 handlePost = postId => {
 if (postId == null) {
      return this.handleRequest("/api/savepost").bind(this);
    }
    return this.handleRequest("/api/updatepost").bind(this);
  };

最佳答案

将所有错误的相关代码移至React组件的范围内。您不能在 React 组件类之外声明和使用函数和状态。 在组件的事件处理程序中,您必须使用“this”调用组件函数。语境。例如:

  onClick={() => this.handlePost....}

关于javascript - 如何修复reactjs中的 "failed to compile"?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58381971/

相关文章:

javascript - 单击按钮时如何将页面的字体颜色变为绿色

JavaScript:获取MySQL时间戳和当前日期之间的天数差异?

javascript - 将值从 Controller 传递到模态页面

javascript - 如何操作 d3 气泡图中的圆圈?

javascript - 在网页上检测 iOS 版本

javascript - 如何使 React-Day-Picker 月份水平并排而不是垂直对齐

javascript - 由外部包导出的 React 和 Webpack 渲染组件

react : Communication between two different components

javascript - 仅当我更改类 Prop 时如何安装组件

reactjs - React Router v4 从 MobX 存储操作导航?