簡體   English   中英

自定義鈎子 function 未在 React 中調用

[英]Custom hook function not being called in React

我正在嘗試調用我的fetchPlants function,但我無法弄清楚為什么它沒有被調用。

/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)

更新它一直在工作。 當我使用 iOS 模擬器對其進行測試時,我需要在計算機上按“ENTER”鍵,因為我使用的是 React Native onEndEditing道具。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM