【问题标题】:React - Too many re-renders after adding onClickReact - 添加 onClick 后重新渲染过多
【发布时间】:2020-01-27 14:54:48
【问题描述】:

我对反应很陌生,我正在玩一个非常简单的网站,该网站从 pokemon api 获取数据。

我想在我的列表项上添加一个 onClick 事件,以便在单击时更改 css。但 当我像这样<Li onClick={setExpand(!expand)}> 将 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>
  )
}

【问题讨论】:

  • &lt;Li onClick={() =&gt; setExpand(!expand)}&gt;
  • 上面的评论是您的解决方案 - 如果没有包装函数,react 将始终在每次渲染时执行setExpand,因为它是一个函数调用。这将导致重新渲染,一旦脚本再次到达那里,它将再次调用该方法,导致另一个重新渲染等等......

标签: javascript reactjs


【解决方案1】:

你需要传递一个回调而不是执行onClick里面的代码

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

【讨论】:

  • 非常感谢,这么简单的解决方案:)
【解决方案2】:

你可以通过handleClick函数

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

【讨论】:

    猜你喜欢
    • 2020-12-06
    • 1970-01-01
    • 1970-01-01
    • 2023-03-30
    • 2020-11-27
    • 2020-11-06
    • 2022-01-02
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多