繁体   English   中英

无法在 js react-native 中设置 state

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

尝试在setState Native 中设置状态时出错。

代码

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;

错误

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

使用状态挂钩

功能组件无权访问setState方法,但无法访问useState挂钩。

useState 钩子通过定义值的名称来工作,例如foo后跟它的 setter。 按照惯例,将 setter 命名为与带有set前缀的 value 的名称相同的名称,即setFoo

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

解决方案

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

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

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

我觉得你有点搞混了

如果您使用 Class 组件,请替换它,因为这是语法

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

和:

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

并查看文档

this.setState在功能组件中是不允许的。 尝试对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