【发布时间】:2021-11-25 00:33:10
【问题描述】:
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;
所以我基本上有 7 个轶事,当我按下按钮投票时,我正在尝试,它应该添加一个投票,我通过数组投票并将其添加到投票数组中的索引来计算, addVote 函数添加了数字,但它不会在屏幕上更新,如果我要再次跳到相同的轶事,它显示得很好,知道吗?
这是不更新的相关 div
<div>Has {votes[selected]} votes </div>
【问题讨论】:
标签: javascript reactjs