0

我正在尝试通过传递 TextInput (onChangeText) 的值来更新 useState() 数组。该代码工作正常,但是每当我点击 onPress (addBook 函数)时,它都会更新/添加数组中的先前文本而不是当前文本。因此,要添加当前文本,我必须单击两次按钮,这会在我的数组中创建重复项。

我可能会犯非常愚蠢的错误,但找不到。任何人都可以帮助。下面是我的全部代码。

import React, { useState } from "react";
import { TextInput, View, Dimensions, TouchableOpacity } from "react-native";
import { MaterialCommunityIcons } from "@expo/vector-icons";
import { Entypo } from "@expo/vector-icons";

const screenHeight = Math.round(Dimensions.get("window").height);

const AddBookName = ({ hidePressed }) => {
  const [book, setBook] = useState();
  const [bookList, setBookList] = useState(["no name"]);

  const addBook = () => {
    setBookList([...bookList, book]);
    console.log(bookList);
  };

  return (
    <View style={{ flexDirection: "row" }}>
      <View style={{ flex: 1 }}>
        <TextInput
          style={{
            fontSize: 20,
            paddingVertical: 10,
            backgroundColor: "#ececec",
            paddingLeft: 10,
          }}
          placeholder="Enter the Book Name"
          placeholderTextColor="grey"
          // value={book}
          onChangeText={(text) => setBook(text)}
          type="text"
        ></TextInput>
      </View>

      <TouchableOpacity
        style={{
          flex: 0.15,
          backgroundColor: "green",
          alignItems: "center",
          justifyContent: "center",
        }}
        onPress={() => addBook()} 
      >
        <View>
          <MaterialCommunityIcons name="check" size={24} color="white" />
        </View>
      </TouchableOpacity>

      <TouchableOpacity
        style={{
          flex: 0.15,
          backgroundColor: "red",
          alignItems: "center",
          justifyContent: "center",
        }}
        onPress={hidePressed}
      >
        <View>
          <Entypo name="cross" size={24} color="white" />
        </View>
      </TouchableOpacity>
    </View>
  );
};

export default AddBookName;

在此处输入图像描述

4

2 回答 2

0

这应该删除重复项:

const addBook = () => {
  setBookList(Array.from(new Set([...bookList, book])));
  console.log(bookList);
};

您还可以将您的书单存储为一组而不是数组。

于 2020-12-03T18:01:28.200 回答
0

添加到列表后尝试清除之前的输入值。

  const addBook = () => {
    if (book) {
        setBookList([...bookList, book]);
        console.log(bookList);
        setBook("");
    }
  };
于 2020-12-03T16:02:34.917 回答