簡體   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