简体   繁体   中英

Can't set state in js react-native

Getting error while trying to setState in React Native.

Code

import React from "react";
import { TextInput, Text, View, Button, Alert } from "react-native";

const UselessTextInput = () => {
  state = { currentDate: "" };

  const setCurentDate = (val) => {
    this.setState({currentDate : val});
  };

  const [value, onChangeText] = React.useState("");

  return (
    <View>
      <Text
        style={{
          alignSelf: "center",
          marginTop: 60,
          fontWeight: "bold",
          fontSize: "25",
        }}
      >
        BirthReminder
      </Text>
      <Text style={{ alignSelf: "center", marginTop: 15, fontSize: 15 }}>
        Enter your friend's birthdate, please
      </Text>
      <TextInput
        clearTextOnFocus={true}
        style={{
          height: 40,
          borderColor: "gray",
          borderWidth: 1,
          marginTop: 20,
          width: 250,
          alignSelf: "center",
        }}
        onChangeText={(value) => setCurentDate(value)}
        value={value}
      />
      <Button title="Add to list"></Button>
    </View>
  );
};

export default UselessTextInput;

Error

TypeError: undefined is not an object (evaluating '_this.setState')

useState Hook

Functional components don't have access to setState method but useState hook.

useState hook works by defining the name of value, eg foo followed by it's setter. It's a convention to name the setter with the same name as that of value with set prefix, ie setFoo

const [foo, setFoo] = useState('hi');
// pass the initial value here -^^-

Solution

import { useState } from 'react';
import { TextInput } from 'react-native';

const Component = () => {
  const [value, setValue] = useState('');

  return <TextInput value={value} onChangeText={setValue} />;
};

I think you got a bit mixed up

replace this as this is the syntax if you use Class component

  state = { currentDate: "" };
  const setCurentDate = (val) => {
    this.setState({currentDate : val});
  };

with:

  const [date, setDate] = React.useState();
  const setCurentDate = (val) => {
    setDate(val);
  };

and have a look at the documentation

this.setState isn't allowed in functional component. Try to use React.useState for currentDate

const [currentDate, setCurrentDate] = React.useState("");

...

const setCurentDate = (val) => {
    setCurrentDate(val);
};

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM