Hen*_*rik 3 javascript reactjs
我对反应还很陌生,我正在玩一个非常简单的网站,它从 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;
};
}
Run Code Online (Sandbox Code Playgroud)
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>
)
}
Run Code Online (Sandbox Code Playgroud)
您需要传递回调而不是执行里面的代码onClick
<Li onClick={() => setExpand(exp => !exp)}>
<Img src={props.src} />
</Li>Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
1638 次 |
| 最近记录: |