clearTimeout在React Native上不起作用

时间:2019-12-01 20:43:20

标签: javascript react-native

我设置了一个超时时间,用于当用户停止键入3秒钟时进行api调用并显示ActivityIndi​​cator。

用完整代码编辑:

import React, { useState, useEffect } from 'react';
import { Text } from 'react-native';
import { ActivityIndicator } from 'react-native';

import {
  Container,
  SearchBar,
  SearchBarInput,
  SearchLoading,
  SearchResultList,
  Product,
} from './styles';

import api from '../../services/api';

export default function Search() {
  const [searchResult, setSearchResult] = useState([]);
  const [searchText, setSearchText] = useState('');
  const [searching, setSearching] = useState(false);
  const [focused, setFocused] = useState(false);

  function renderProduct({ item }) {
    return <Text>Oi</Text>;
  }

  let timer;

  function handleChangeText(text) {
    setSearching(false);
    setSearchText(text);

    clearTimeout(timer);

    timer = setTimeout(() => setSearching(true), 3000);
  }

  useEffect(() => {
    async function search() {
      const response = await api.get(`products?search=${searchText}`);

      setSearchResult(response.data);
      setSearching(false);
    }
    if (searching) {
      search();
    }
    // eslint-disable-next-line react-hooks/exhaustive-deps
  }, [searching]);

  return (
    <Container>
      <SearchBar focused={focused}>
        <SearchBarInput
          placeholder="Pesquisar..."
          onChangeText={handleChangeText}
          onFocus={() => setFocused(true)}
          onBlur={() => setFocused(false)}
          value={searchText}
        />
        {searching && (
          <SearchLoading>
            <ActivityIndicator size="small" color="#000" />
          </SearchLoading>
        )}
      </SearchBar>
      <SearchResultList
        data={searchResult}
        keyExtractor={item => String(item.id)}
        renderItem={renderProduct}
      />
    </Container>
  );
}

.............................................. < / p>

但是它不能正常工作:

https://user-images.githubusercontent.com/54718471/69919848-14680a00-1460-11ea-9047-250251e42223.gif

1 个答案:

答案 0 :(得分:1)

请记住,函数主体在每个渲染器上运行。因此,每次重新渲染组件时,对现有timer的引用都会丢失。

您可以使用useRef钩子(https://reactjs.org/docs/hooks-reference.html#useref)来保持跨渲染的稳定引用。

const timerRef = useRef(null);

function handleChangeText(text) {
  setSearching(false);
  setSearchText(text);

  clearTimeout(timerRef.current);

  timerRef.current = setTimeout(() => setSearching(true), 3000);
}