微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

React Native 'setState' 不存在?

如何解决React Native 'setState' 不存在?

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

enter image description here

我目前的代码

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;

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

解决方法

状态应该在构造函数里面,改成这样:

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

   this.state = {
    patients: [],firstName: "",lastName: "",nin: "",};
 }

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。