动态搜索未生成,数据始终在控制台中显示未定义

Dynamic Search is not getting build, Data is always showing undefined in the console

这是我用来构建搜索栏的代码,该搜索栏会像 facebook 或 Instagram 一样动态显示搜索栏下方的结果 do.But 它没有发生我尝试了多次但是当我将值放在它调用一次的搜索中,然后我再次刷新它以获取 Api 数据。

import React, { useEffect, useState } from 'react';
import { createStackNavigator } from '@react-navigation/stack';
import searchScreen from './searchScreen';
import { View, Text, Dimensions, TextInput } from 'react-native';
import colors from '../../../res/colors';

export default function searchNavigator() {
  const Stack = createStackNavigator();
  const [text, setText] = useState("");
  const [dataSource, setDataSource] = useState([]);

  useEffect(() => {
    async function getData(text) {
      const api = 'http://188.166.189.237:3001/api/v1/profile/';

      await fetch(api + text)
        .then((response) => response.json())
        .then((responseJson) => {
          setDataSource(responseJson)
          console.log("Search Data", dataSource);
        })
        .catch((error) => {
          console.log("Seach error", error);
        })
    };
    getData();
  }, []);

这是搜索输入,我将连接到 Api 的搜索文本的值放入其中。如果有人能帮我解决这个问题,那就更感激了,在此先感谢。

 <View style={{
              marginHorizontal: 5, marginVertical: 10, justifyContent: "center",
              alignItems: "center"
            }}>
              <TextInput
                style={{
                  backgroundColor: colors.textInputBackground,
                  height: 35,
                  width: Dimensions.get('screen').width - 10,
                  fontWeight: 'bold',
                  borderRadius: 10,
                  paddingStart: 20,
                  fontSize: 16,
                  color: 'white',
                }}
                onChangeText={(text) => setText(text)}
                placeholder="Search"
                placeholderTextColor={colors.textFaded2}
              />
            </View>

您应该为 useEffect 添加依赖项。 getData 在您更改搜索时未被调用。每当您的 text 状态发生变化时,下面的代码将 运行 您的 useEffect

useEffect(() => {
    async function getData(text) {
      const api = 'http://188.166.189.237:3001/api/v1/profile/';

      await fetch(api + text)
        .then((response) => response.json())
        .then((responseJson) => {
          setDataSource(responseJson)
          console.log("Search Data", dataSource);
        })
        .catch((error) => {
          console.log("Seach error", error);
        })
    };
    getData();
  }, [text]);