如何在这个 React class 中进行抓取?

How to make fetch in this React class?

我知道如何使用我的反应组件中的函数获取到我的后端,但我需要一个下拉菜单所以我在 react-select 页面中找到了一个示例,但该示例是在 class.

我在互联网上找到的干净示例是这样的,对于导入 react-select 它需要 运行 命令 npm install react-select:

import React, { Component, Fragment, useEffect } from "react";
import Select from "react-select";

const options = [
  { value: "red", label: "red" },
  { value: "blue", label: "blue" },
  { value: "green", label: "green" }
];

export default class CrearPost extends Component {
  state = {
    selectedOption: null
  };
  handleChange = selectedOption => {
    this.setState({ selectedOption });
    // Option selected: { value: "red", label: "red" }
    console.log(`Option selected:`, selectedOption);
  };
  render() {
    return (
      <div align="center">
      <Fragment>
        <Select
          className="basic-single"
          classNamePrefix="select"
          defaultValue={options[0]}
          isDisabled={false}
          isLoading={false}
          isClearable={true}
          isRtl={false}
          isSearchable={true}
          name="color"
          options={options}
          onChange={this.handleChange}
        />
      </Fragment>
      <input
        type="text"
        placeholder="body"
      />
      <button>
        Submit post
      </button>
      </div>
    );
  }
}

看起来像这样:

所以我决定尝试做fetch,我尝试的是这样的:

import React, { Component, Fragment, useEffect, useState } from "react";
import Select from "react-select";
import { useHistory } from "react-router-dom"; 

const options = [
  { value: "red", label: "red" },
  { value: "blue", label: "blue" },
  { value: "green", label: "green" }
];

export default class CrearPost extends Component {
  state = {
    selectedOption: null
  };
  handleChange = selectedOption => {
    /*I added all this*/ 
  const [title, setTitle] = useState("");
  const [body, setBody] = useState("");

    const PostData = () => {
      fetch('/createpost', { /*This route is in my nodejs server*/ 
        method:'post',
        headers:{
          'Content-Type':'application/json',
          Authorization: "Bearer " + localStorage.getItem("jwt")
        },
        body:JSON.stringify({
          title,
          body
        })
      }).then(res=>res.json())
      .then(data=>{
        console.log(data)
        if(data.error){
          alert(data.error)
        }
        else{
          alert('Post created')
          history.push('/')
        }
      }).catch(err=>{
        console.log(err)
      })
    }
  };
  render() {
    return (
      <div align="center">
      <Fragment>
        <Select
          className="basic-single"
          classNamePrefix="select"
          defaultValue={options[0]}
          isDisabled={false}
          isLoading={false}
          isClearable={true}
          isRtl={false}
          isSearchable={true}
          name="color"
          options={options}
          value={title}/*I added this*/ 
          onChange={(e) => setTitle(e.target.value)}/*I added this*/ 
        />
      </Fragment>
      <input
        type="text"
        placeholder="body"
        value={body}/*I added this*/ 
        onChange={(e) => setBody(e.target.value)}/*I added this*/ 
      />
      <button onClick={() => PostData()}/*I added this*/>
        Submit post
      </button>
      </div>
    );
  }
}

但是我在我的项目中遇到了这个失败:

希望有人能帮帮我,谢谢。

根据您的错误消息截图,它说 useState 不能用于基于 class 的组件。 useState 是一个新的 React 钩子,用于为 class-less 功能组件提供状态功能。 在基于 class 的组件中,您可以像我们以前那样使用 state = {...}

所以而不是这些行...

  const [title, setTitle] = useState("");
  const [body, setBody] = useState("");

将它们更改为...

  state = {
    selectedOption: null,
    title: "",
    body: ""
  };

并将所有 setBodysetTitle 调用更改为状态更改调用。

Class组件是有状态组件,有自己的状态。所以你不需要在 class 组件中使用 useState 。只需尝试将您的状态更改为:

this.state = {
    title: "",
    body: ""
  };

并且不要忘记删除您的状态常量