javascript - 在 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)
正常。
解决方案
更新它一直在工作。当我使用 iOS 模拟器对其进行测试时,我需要在我的计算机上点击“ENTER”键,因为我使用的是 React NativeonEndEditing
道具。
推荐阅读
- xml - 通过 .po 文件将 xml 中定义的翻译添加到 Odoo 的正确方法是什么?
- python - 使用 fit=stats.norm 在 sns.distplot 中将 y 轴更改为百分比
- android - Android 10:在 android Q 中选择视频时崩溃
- delphi - TUniQuery (UniDac TUniQuery) Last 和 First 方法是直接跳转还是逐条记录滚动
- html - 有没有办法在 SASS 中对选择器进行分组?
- node.js - 调用异步函数之前的行
- ruby - 配置错误的 Apache 服务器未正确实现 SSL
- c# - 使用 c# 连接 AWS cassandra
- android-studio - AndroidStudio在编辑器中选择手机号码
- javascript - 如何在不更改子元素的情况下更改元素 innerText