javascript - Promise:从 React Native Component Prop 函数返回 Promise 时未调用 .then()
问题描述
我有一个反应原生组件,如下所示:
export const SearchBar = (props: SearchListProps) => {
const {
data,
matchingFunction,
listItemVariant,
onChange,
onSubmit,
renderItem,
...rest
} = props;
const animatedValue = useRef(new Animated.Value(0));
const [searchValue, setSearchValue] = useState('');
const [isFocused, setFocused] = useState(false);
const listData = useRef([...data]);
if (isFocused) {
Animated.timing(animatedValue.current, {
duration: 100,
toValue: 1,
useNativeDriver: true,
}).start();
}
useEffect(() => {
const promise = props?.dataSource(searchValue);
console.log('RETURNED: ' + JSON.stringify(promise));
promise
.then((result: any) => {
console.log('RESULT: ' + JSON.stringify(result));
})
.catch((e) => console.log(e));
}, [searchValue]);
//... rest of the code
然后我在这样的地方使用这个组件:
<SearchBar
listItemVariant={'withImage'}
dataSource={async (query?: string) => {
console.log('Query Passed: ' + query);
return new Promise<ListItem[]>((resolve, _) => {
resolve([
{
title: 'Paneer Bhurji',
subTitle: 'Delicious',
imageSource:
'https://homepages.cae.wisc.edu/~ece533/images/peppers.png',
},
{ title: 'Paneer Butter Masala', subTitle: 'High Protein' },
{
title: 'Chicken',
imageSource:
'https://homepages.cae.wisc.edu/~ece533/images/peppers.png',
},
]);
});
}}
// ...rest of the code
问题是组件中没有调用 .then() 。 控制台打印以下语句:
- 查询通过:
- 回来: {}
当我返回一个包含一些数据的承诺时,我不确定为什么会返回 {}。
其他日志(在 useEffect 的 .then() 内)没有被打印出来。 所以本质上, .then() 方法永远不会被调用。
解决方案
推荐阅读
- angular - 当服务需要导入另一个服务时如何避免“循环依赖”错误
- python - 在 pandas 中读取具有非 ascii 字符集的 CSV,然后存储在 PGSQL 中
- homebrew - 自制软件在 MacOS Big Sur 上失败
- typescript - 在 Typescript 中将非 null 值与 null 进行比较时是否可能会收到警告?
- r - ggplot:用图中的点数更新构面标签
- maven - 列出maven中所有缺少的依赖项
- azure - 如何将保留历史记录(时间戳和版本)的 Databricks 表复制到新订阅中的另一个 Databricks?
- swift - 如何在Firebase / Swift中更新字段等于的文档字段
- powershell - PowerShell:Visual Studio Code - 不反映模块中的更改
- serverless-framework - 使用无服务器离线在本地捕获 Dynamo 流事件