【问题标题】:React Native 'setState' does not exist?React Native 'setState' 不存在?
【发布时间】:2021-01-10 13:08:44
【问题描述】:

我正在尝试使用 Axios 发布帖子,以便将人员添加到我的数据库中。我不断收到“'PersonForm'(文件名)类型上不存在属性'setState'”的错误消息。

我目前的代码:

import React from 'react';
import { View, TextInput, Text, Button } from 'react-native';
import { PersonForCreate } from '../data/person';

import axios from "axios";

class PersonForm extends React.Component {
state = {
    patients: [],
    firstName: "",
    lastName: "",
    nin: "",
  };

  constructor(props) {
    super(props);
    this.addPatient = this.addPatient.bind(this);
  }

  addPatient() {
    let patientAdd = {
      firstName: this.state.firstName,
      lastName: this.state.lastName,
      nin: this.state.nin,
    };

    axios.post(`http://127.0.0.1:8000/person`, patientAdd).then((res) => {
      console.log(res);
      console.log(res.data);
    });
  }

render() {
    return (
        <View>
            <TextInput 
                key="firstName"
                placeholder="First Namee"
                onChange={(e) => {
                    this.setState({ firstName: e.target.value });
                  }}            
            />
            <TextInput 
                key="lastName"
                placeholder="Last Name"
                onChange={(e) => {
                    this.setState({ lastName: e.target.value });
                  }}              
            />  
            <TextInput 
                key="nin"
                placeholder="National Insurance Number"
                onChange={(e) => {
                    this.setState({ nin: e.target.value });
                  }}              
            />      
            <Button title="Submit" onPress={this.addPatient}></Button>                          
        </View>
    )
}
}

export default PersonForm;

如果有人知道如何解决此问题或如何正确执行此操作,将不胜感激!

【问题讨论】:

    标签: reactjs forms react-native form-submit setstate


    【解决方案1】:

    状态应该在构造函数内部,将其更改为:

      constructor(props) {
        super(props);
        this.addPatient = this.addPatient.bind(this);
    
       this.state = {
        patients: [],
        firstName: "",
        lastName: "",
        nin: "",
      };
     }
    

    【讨论】:

    • 如果将状态放入构造函数中,如何将值添加到“let patientAdd”?
    • @JensPanis 与您在 addPatient 中所做的相同,这将起作用
    • “只读类型上不存在属性名”是我目前在 addPatient 中的 3 个值遇到的错误。
    • @JensPanis 你在使用 TS 吗?
    • @JensPanis 将此添加到您的类声明 class PersonForm extends React.Component&lt;{},any&gt;{
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2019-09-26
    • 2018-12-23
    • 1970-01-01
    • 2020-09-08
    • 1970-01-01
    • 2021-05-18
    • 2017-11-17
    相关资源
    最近更新 更多