首页 > 解决方案 > 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() 。 控制台打印以下语句:

  1. 查询通过:
  2. 回来: {}

当我返回一个包含一些数据的承诺时,我不确定为什么会返回 {}。

其他日志(在 useEffect 的 .then() 内)没有被打印出来。 所以本质上, .then() 方法永远不会被调用。

标签: javascriptandroidiosreactjsreact-native

解决方案


推荐阅读