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

标签 javascript reactjs

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

Image of the site - screenshot

我想在我的列表项上添加一个 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>

关于javascript - React - 添加 onClick 后重新渲染太多,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59933546/

相关文章:

javascript - 我的代码在以对象文字表示法创建方法时有什么问题?

javascript - 返回和换行?

javascript - 如何使用CSS在顶部导航栏上添加后退按钮?

javascript - 如何用material-ui设置时钟(timePicker)的颜色?

javascript - Material -ui选择器: how to hide text field and open modal with button

reactjs - 需要检查提交的值是否大于当前值

javascript - 如何检查javascript日期是否来自指定的一周前?

javascript - jQuery - 将变量传递给点击功能

javascript - 将类对象传递给 ReactJS 组件

reactjs - Google Maps React - 没有重载与此调用匹配