开发者问题收集

无法在 js react-native 中设置状态

2021-01-23
327

在 React Native 中尝试 setState 时出错。

代码

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 (evaluating '_this.setState')

3个回答

useState Hook

函数式组件无法访问 setState 方法,但可以访问 useState 钩子。

useState 钩子通过定义值的名称来工作,例如 foo 后跟其 setter。约定俗成地将 setter 命名为与值相同的名称,并加上 set 前缀,即 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} />;
};
Vinay Sharma
2021-01-23

this.setState 在功能组件中不可用。请尝试对 currentDate 使用 React.useState >

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

...

const setCurentDate = (val) => {
    setCurrentDate(val);
};
michael
2021-01-23

我觉得你有点搞混了

用:

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

替换此代码,因为这是使用 Class 组件时的语法

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

并查看 文档

Kevin Amiranoff
2021-01-23