React Native 中的状态不更新

问题描述

我无法在 React Native 中更新 useState 编码中的状态。 组件样式为 TextInput。 我做错了什么,状态没有看到来自 SearchField 的文本输入?

export const TabOnescreen: FC<IProps> = ({ navigation }) => {
  const [userName,setUserName] = useState("jan");

  useEffect(() => {
    fetch(`https://api.github.com/users/${userName}`)
      .then((response) => response.json())
      .then((json) => console.log(json));
  },[userName]);

  const handleUserName = (value: string) => {
    setUserName(value);
  };

  return (
    <StyledContainer>
      <SearchField onChangeText={(value: string) => handleUserName(value)} />
      <Text>{userName}</Text>
      <DetailsField backgroundColor={colors.whiteColor} />
      <Button
        color={colors.buttonBackground}
        title="Show more"
        onPress={() => {
          navigation.navigate("DetailsScreen");
        }}
      />
    </StyledContainer>
  );
};

解决方法

您需要将 userName 的值赋予 SearchField:

 <SearchField value={userName} onChangeText={(value: string) => handleUserName(value)} />

如果没有设置属性值,您的事件将包含正确的新值

,

不幸的是,有些事情还是不行。我已经添加了 value={userName} 但它看起来是这样的。 感谢您的反馈。

在此处输入图片说明

enter image description here

相关问答

Selenium Web驱动程序和Java。元素在(x,y)点处不可单击。其...
Python-如何使用点“。” 访问字典成员?
Java 字符串是不可变的。到底是什么意思?
Java中的“ final”关键字如何工作?(我仍然可以修改对象。...
“loop:”在Java代码中。这是什么,为什么要编译?
java.lang.ClassNotFoundException:sun.jdbc.odbc.JdbcOdbc...