反应-添加onClick后重新渲染过多

时间:2020-01-27 14:54:48

标签: javascript reactjs

我是一个非常新的反应者,并且我正在与一个非常简单的站点一起玩,该站点从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>
  )
}

2 个答案:

答案 0 :(得分:3)

您需要传递回调,而不是在onClick中执行代码

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

答案 1 :(得分:1)

您可以通过handleClick函数

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