簡體   English   中英

React - 添加 onClick 后重新渲染太多

[英]React - Too many re-renders after adding onClick

我對反應還很陌生,我正在玩一個非常簡單的網站,該網站從 pokemon api 獲取數據。

網站圖片 - 屏幕截圖

我想在我的列表項上添加一個 onClick 事件以在單擊時更改 css。 但是,當我像這樣將 setExpand(!expand) 添加到我的列表項<Li onClick={setExpand(!expand)}>我收到一個錯誤消息,告訴我“錯誤:重新渲染太多。React 限制渲染次數以防止一個無限循環”,我無法理解。

主要的

//Styling
const Section = styled.section`
  margin-top: 100px;
`;

const Ul = styled.ul`
  margin:0;
  padding:0;
  list-style:none;
  display: flex;
  justify-content: center;
  flex-wrap: wrap;
`;

const Main = styled.main`
  max-width: 1200px;
  margin: 0 auto;
  width: 100%;
`;

export default function Test() {
  //States
  const [pokemonArray, newPokemon] = useState([]);

  //Hooks
  useEffect(() => {
    (async () => {
      const dataArray = [];
      for (let i = 1; i < 6; i++) {
        let data = await fetch('https://pokeapi.co/api/v2/pokemon/' + i).then(res => res.json());
        dataArray.push(data);
      }

      newPokemon(dataArray);
    })()
  }, []);

  //Render
  return (
    <Route exact path="/test">
      <Main>
        <Section>
          <Ul>
            {articleTemplate()}
          </Ul>
        </Section>
      </Main>
    </Route>
  );

  //Functions
  function articleTemplate() {
    const components = []
    pokemonArray.forEach((elm, index) => {
      components.push(<Li key={index} src={elm.sprites.front_default} />)
    })
    return components;
  };
}

列表項組件

import React, { useState } from 'react';
import styled from 'styled-components';

const Li = styled.li`
  width: 50px;
  height: 50px;
  margin: 25px;
  box-sizing: border-box;
  background:url('https://via.placeholder.com/500x500');
`;

const Img = styled.img`
  width: 100%;
  height: 100%;
  object-fit: cover;
`;

export default function Image(props) {
  const [expand, setExpand] = useState(false);

  return (
    <Li onClick={setExpand(!expand)}>
      <Img src={props.src} />
    </Li>
  )
}

你需要傳遞一個回調而不是執行onClick里面的代碼

 <Li onClick={() => setExpand(exp => !exp)}> <Img src={props.src} /> </Li>

您可以通過handleClick函數

export default function Image(props) {
  const [expand, setExpand] = useState(false);
  const handleClick=()=>{
   setExpand(!expand);
  }
  return (
    <Li onClick={handleClick}>
      <Img src={props.src} />
    </Li>
  )
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM