gpt4 book ai didi

javascript - 在父状态更改后 react 子组件不重新渲染

转载 作者:行者123 更新时间:2023-12-05 04:51:49 25 4
gpt4 key购买 nike

我是 React 的新手,正在尝试创建一个简单的纸牌游戏。单击卡片时,应选择它并为其分配类名“selectedCard”。所以当它重新渲染时,选中的卡片会被抬起。但是,选中的卡片并没有抬起onClick,我猜是它没有重新渲染。

这是我的代码片段:

播放器.js:

const Player = (props) =>{
const [selectedCards, setSelectCard] = useState([]);

const selectCard = (card) => {
let newSelectedCards = selectedCards
if(newSelectedCards.includes(card) ) {
newSelectedCards.splice(newSelectedCards.indexOf(card), 1)
} else {
newSelectedCards.push(card)
}
setSelectCard(newSelectedCards)
console.log('changed');
}


return(
<div className="player-container">
{props.cards && props.cards.map((card, i) => {
let selected = selectedCards.includes(card)
return(<Card key={i} card={card} user="player" selectCard={selectCard} selected={selected}/>)
}
)}
)
}

卡片.js

const Card = (props) =>{
const path = props.card.imagePath
const [selected, setSelected] = useState(props.selected)

useEffect(() => { setSelected(props.selected) }, [props.selected]);
{/*My effort to make it work*/}

const classname = (selected) ? "selectedcard" : ""
return(
<img onClick={() => props.selectCard(props.card)} className={"card " + classname} alt = "card-image" src={images[path]}/>)
}

CSS

.selectedcard{
margin-bottom: 40px;
border-radius: 6px;
box-shadow: 0px 0px 5px #fff !important;
}

最佳答案

你不应该在更新状态时改变它,如果你这样做,React 会在引用中看到你的引用是相同的,并假设没有任何改变并且不会触发重新渲染。

更新 react 状态时遵循不变性的概念。您可以使用 Array.prototype.slicespread syntax 更新它以删除元素并使用 Array.prototype.concat 添加元素

const selectCard = (card) => {
let newSelectedCards =[];
if(newSelectedCards.includes(card) ) {
const index = selectedCards.indexOf(card)
newSelectedCards = [...selectedCards.slice(0, index), ...selectedCards.slice(index + 1)]
} else {
newSelectedCards = selectedCards.concat([card]);
}
setSelectCard(newSelectedCards)
console.log('changed');
}

关于javascript - 在父状态更改后 react 子组件不重新渲染,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/66767448/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com