首页 > 解决方案 > 在我尝试在 useState 数组中搜索元素后,我的组件重新渲染

问题描述

我目前正在构建一个 React 项目,因此我进行了搜索输入,当我在该输入字段中键入内容时,我的孔组件重新呈现,导致 API 召回并删除我的输入中的文本。我尝试将搜索组件与 Home 组件合并,并出现相同的问题。我希望我的组件只调用一次 api,并且我试图根据输入类型过滤响应。

请帮忙!!这是我的 Home 组件:

import { useContext, useEffect, useState } from 'react';
import styled from 'styled-components';
import CountryThumb from '../Components/CountryThumb';
import ThemeContext from '../Components/ColorPalette';
import { Themes } from '../Components/ColorPalette';
import Search from '../Components/Search';
import Filter from '../Components/Filter';

const Grid = styled.main`
  width: 100%;
  display: grid;
  grid-template-columns: repeat(4, 1fr);
  column-gap: 60px;
  row-gap: 40px;
  @media (max-width: 375px) {
    grid-template-columns: repeat(1, 1fr);
  }
`;
export default function Home() {
  const [Countries, setCountries] = useState([]);
  const [SearchTerms, setSearchTerms] = useState('');
  const { Theme } = useContext(ThemeContext);
  const style = Theme == 'light' ? Themes.light : Themes.dark;

  useEffect(() => {
    getCountries();
  }, []);
  const Main = styled.main`
    display: flex;
    flex-wrap: wrap;
    padding: 20px 100px;
    background-color: ${Theme == 'light' ? style.background : style.background};
    @media (max-width: 375px) {
      padding: 40px 25px;
    }
  `;

  const getCountries = () => {
    axios
      .get('https://restcountries.eu/rest/v2/all')
      .then((res) => setCountries(res.data))
      .catch((err) => console.log(err));
  };

  return (
    <>
      <Main>
        <Search handleSearch={(e) => setSearchTerms(e.target.value)} />
        <Filter />
        <Grid>
          {Countries.slice(0, 12)
            .filter((e) => {
              if (SearchTerms == '') {
                return e;
              } else if (
                e.name.toLowerCase().includes(SearchTerms.toLowerCase())
              ) {
                return e;
              }
            })
            .map((e) => (
              <CountryThumb props={e} />
            ))}
        </Grid>
      </Main>
    </>
  );
}

这是我的搜索组件:

import { useContext, useState } from 'react';
import styled from 'styled-components';
import ThemeContext, { Themes } from './ColorPalette';
function Search({ handleSearch }) {
  const { Theme } = useContext(ThemeContext);
  const style = Theme == 'light' ? Themes.light : Themes.dark;
  const Svg = styled.svg`
    width: 24px;
    height: 24px;
    color: ${style.text};
  `;
  const Wrapper = styled.div`
    background-color: ${style.element};
    border-radius: 5px;
    box-shadow: 0 5px 10px ${style.shadow};
    display: flex;
    align-items: center;
    padding: 0 20px;
    margin: 40px 0;
  `;
  const CInput = styled.input`
    border: none;
    outline: none;
    padding: 15px 120px 15px 20px;
    font-size: 1rem;
    color: ${style.text};
    background: none;
  `;
  return (
    <>
      <Wrapper>
        <Svg
          xmlns='http://www.w3.org/2000/svg'
          class='h-6 w-6'
          fill='none'
          viewBox='0 0 24 24'
          stroke='currentColor'
        >
          <path
            strokeLinecap='round'
            strokeLinejoin='round'
            strokeWidth='2'
            d='M21 21l-6-6m2-5a7 7 0 11-14 0 7 7 0 0114 0z'
          />
        </Svg>
        <CInput
          type='text'
          name='Search'
          onInput={handleSearch}
          placeholder='Search for a country ...'
        />
      </Wrapper>
    </>
  );
}

export default Search;

标签: javascriptreactjs

解决方案


每当您更改状态中的任何内容时,您的组件都会重新呈现,因此这是正常行为。但是你在 useEffect 中有调用 api 的依赖数组,所以这个函数应该只运行一次,也许你之前没有数组而忘记保存。


推荐阅读