简体   繁体   English

无法在 js react-native 中设置 state

[英]Can't set state in js react-native

Getting error while trying to setState in React Native.尝试在setState 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') TypeError: undefined is not an object(评估'_this.setState')

useState Hook使用状态挂钩

Functional components don't have access to setState method but useState hook.功能组件无权访问setState方法,但无法访问useState挂钩。

useState hook works by defining the name of value, eg foo followed by it's setter. useState 钩子通过定义值的名称来工作,例如foo后跟它的 setter。 It's a convention to name the setter with the same name as that of value with set prefix, ie setFoo按照惯例,将 setter 命名为与带有set前缀的 value 的名称相同的名称,即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如果您使用 Class 组件,请替换它,因为这是语法

  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. this.setState在功能组件中是不允许的。 Try to use React.useState for currentDate尝试对currentDate使用React.useState

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

...

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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