Moh*_*bil 8 javascript reactjs
import React, { useState } from "react";
const App = () => {
const anecdotes = [
"If it hurts, do it more often",
"Adding manpower to a late software project makes it later!",
"The first 90 percent of the code accounts for the first 10 percent of the development time...The remaining 10 percent of the code accounts for the other 90 percent of the development time.",
"Any fool can write code that a computer can understand. Good programmers write code that humans can understand.",
"Premature optimization is the root of all evil.",
"Debugging is twice as hard as writing the code in the first place. Therefore, if you write the code as cleverly as possible, you are, by definition, not smart enough to debug it.",
"Programming without an extremely heavy use of console.log is same as if a doctor would refuse to use x-rays or blood tests when diagnosing patients",
];
const [selected, setSelected] = useState(0);
const [votes, setVotes] = useState([0, 0, 0, 0, 0, 0, 0]);
function getRandomInt(max) {
return Math.floor(Math.random() * max);
}
function pickRandomNumber() {
setSelected(getRandomInt(anecdotes.length));
}
function addVote() {
const newVotes = votes;
newVotes[selected] += 1;
setSelected(selected);
setVotes(newVotes);
}
return (
<div>
<div>{anecdotes[selected]}</div>
<div>Has {votes[selected]} votes </div>
<button onClick={addVote}>vote</button>
<button onClick={pickRandomNumber}>next anecdote</button>
</div>
);
};
export default App;
Run Code Online (Sandbox Code Playgroud)
所以我基本上有 7 个轶事,我尝试当我按下投票按钮时,它应该添加一个投票,我通过数组投票并向投票数组中的索引添加 1 来计算,数字被添加通过 addVote 函数,但它不会在屏幕上更新,如果我再次跳到相同的轶事,它显示得很好,知道吗?
这是不更新的相关 div
<div>Has {votes[selected]} votes </div>
Run Code Online (Sandbox Code Playgroud)
Dre*_*ese 16
这里的问题是状态突变之一。您正在改变对当前状态的引用,然后将其保存回状态。状态引用永远不会改变,因此 React 不会“看到”任何内容已更新,也不会触发重新渲染。
function addVote() {
const newVotes = votes; // <-- reference to state
newVotes[selected] += 1; // <-- state mutation!!
setSelected(selected);
setVotes(newVotes); // <-- reference saved back into state
}
Run Code Online (Sandbox Code Playgroud)
要解决这个问题,您必须创建一个新的状态引用。请记住,数组也是按引用复制的,因此数组元素需要是新引用。此外,每当您递增计数或下一个状态值取决于任何先前的状态值时,您都应该使用功能状态更新来从先前的状态正确更新。
function addVote() {
setSelected(selected);
setVotes(votes => votes.map((vote, i) => i === selected ? vote + 1 : vote);
}
Run Code Online (Sandbox Code Playgroud)