首页 > 解决方案 > 在 React 中未调用自定义钩子函数

问题描述

我正在尝试调用我的fetchPlants函数,但我无法弄清楚为什么它没有被调用。

/screens/RecipeScreen.js

import usePlants from '../hooks/usePlants';

// Call our custom hook
const [fetchPlants, plantResults] = usePlants();

// ...other code...

<RecipeSearch
  recipeSearch={recipeSearch}
  onRecipeSearchChange={setRecipeSearch}
  onRecipeSearchSubmit={() => fetchPlants(recipeSearch)}
/>

/components/RecipeSearch.js

const RecipeSearch = ({
  onRecipeSearchChange,
  onRecipeSearchSubmit,
  recipeSearch,
}) => {
  return (
    console.log(recipeSearch); // This prints out nicely...
    <View>
      <View>
        <TextInput
          placeholder='Find a plant...'
          value={recipeSearch}
          onChangeText={onRecipeSearchChange}
          onEndEditing={onRecipeSearchSubmit}
        />
      </View>
    </View>
  );
};

/hooks/usePlants.js

import { useState, useEffect } from 'react';
import plantsApi from '../api/plants';

export default () => {

  const [plantResults, setPlantResults] = useState([]);

  const fetchPlants = async searchTerm => {
    console.log('searchTerm... HERE IS THE QUERY', searchTerm); // this never gets hit
    try {
      const response = await plantsApi.get('').then(response => {
        console.log(response);
        setPlantResults(response);
      });
    } catch (err) {
      console.log(err);
    }
  };


  return [fetchPlants, plantResults];
};

我最初认为可能是我调用fetchPlants()得太早了(之前recipeSearch有任何状态),但我不这么认为,因为它仍然能够console.log(searchRecipe)正常。

标签: javascriptreactjsreact-native

解决方案


更新它一直在工作。当我使用 iOS 模拟器对其进行测试时,我需要在我的计算机上点击“ENTER”键,因为我使用的是 React NativeonEndEditing道具。


推荐阅读