The*_*que 4 javascript state reactjs
我cards在我的州显示地图功能。状态如下所示:
[{ position: "0", state: "pending" },
{ position: "1", state: "pending" },
{ position: "2", state: "pending" }]
Run Code Online (Sandbox Code Playgroud)
在一个函数中,我将“状态”从“待定”更改为“正确”,但它不会刷新页面上的任何内容。
export const Card: React.FC<ICardOwnProps> = ({ }) => {
const [rollingCards, setRollingCards] = useState<IRollingCard[]>([{ position: "0", state: "pending" }, { position: "1", state: "pending" }, { position: "2", state: "pending" }])
const handleClick = () => {
let newArray = rollingCards;
newArray.splice(0, 1)
setRollingCards(newArray);
}
useEffect(() => { console.log("check changes") })
return (
<StyledCard className="Card">
{rollingCards.map((v, i, a) =>
<Container key={i} className={"position" + v.position} >{v.state}</Container>
)}
<div className="card__container--button">
<button onClick={handleClick}>Oui</button>
<button>Non</button>
{rollingCards[0].state}
</div>
</StyledCard>
);
}
Run Code Online (Sandbox Code Playgroud)
从现在开始,什么都没有改变,但是当我添加一个与滚动卡同时更新的新状态片时,它会更新。我添加了一个计数器,然后它会更新页面。
(我也试过拼接数组看React会不会更新,结果没有)
知道为什么我有这种奇怪的行为吗?
谢谢。
var*_*ons 20
这是因为 React 在决定重新渲染时会对 props/state 进行引用相等性比较。
newArray 与 rollingCards 具有相同的引用,因此功能组件不会在 setRollingCards 上重新呈现
改变
setRollingCards(newArray)
Run Code Online (Sandbox Code Playgroud)
到
setRollingCards([...newArray])
Run Code Online (Sandbox Code Playgroud)
这将使用 newArray 中的元素创建一个新数组(新引用)
工作解决方案:https : //codesandbox.io/s/admiring-wave-9kgqq
| 归档时间: |
|
| 查看次数: |
4554 次 |
| 最近记录: |