首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
MCP广场
社区首页 >问答首页 >在尝试搜索useState数组中的元素后,组件重新呈现

在尝试搜索useState数组中的元素后,组件重新呈现
EN

Stack Overflow用户
提问于 2021-09-01 15:53:26
回答 1查看 39关注 0票数 0

我目前正在构建一个React项目,所以我输入了一个搜索输入,当我在该输入字段中输入一些内容时,我的hole组件会重新呈现,导致API调用并删除输入中的文本。我尝试将搜索组件和Home组件合并,同样的问题也出现了。我希望我的组件只调用api一次,并且我正在尝试根据输入类型过滤响应。

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

代码语言:javascript
运行
复制
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>
    </>
  );
}

这是我的搜索组件:

代码语言:javascript
运行
复制
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;
EN

回答 1

Stack Overflow用户

发布于 2021-09-01 16:02:00

无论何时你改变状态,你的组件都会重新渲染,所以这是正常的行为。然而,你在调用api的useEffect中有依赖数组,所以这个函数应该只运行一次,可能你以前没有数组,忘记了保存。

票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/69017060

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档