javascript - 使用 useState 时如何更改对象中的值
问题描述
到目前为止,我正在学习 React,当我想单击“投票”按钮并且对该故事的投票增加时,我遇到了问题。有人可以指导我吗?
JavaScript 代码:
import React, { useState } from "react";
import ReactDOM from "react-dom";
import "./styles.css";
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 90 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."
];
function Button(props) {
return <button onClick={props.event}>{props.text}</button>;
}
function App() {
const [selected, setSelected] = useState(0);
const [points, setPoints] = useState({
0: 0,
1: 0,
2: 0,
3: 0,
4: 0,
5: 0
});
function next() {
setSelected(Math.floor(Math.random() * anecdotes.length));
}
function vote() {
}
return (
<>
<h1>Anecdote of the day</h1>
<p>{anecdotes[selected]}</p>
<p>has {points[selected]} votes</p>
<Button text="Vote" event={vote} />
<Button text="Next anecdote" event={next} />
</>
);
}
const rootElement = document.getElementById("root");
ReactDOM.render(<App />, rootElement);
谢谢你。
解决方案
我认为这里每个人都缺少的最重要的是
setPoints( points => { //new Points return newPoints})
如果您从以前的值设置状态,那么您需要为 setState 传递一个函数以避免竞争情况。
如果 state 是一个对象,那么改变它就没有用处,因为引用将是相同的旧引用并且 react 不会重新渲染。
为了解决这个问题,我通常做的是
setPoints( points => { let newPoints = JSON.parse(JSON.stringify(points)); //change newPoints; return newPoints })
我选择
JSON.parse(JSON.stringiy(points))
rathar的主要原因{...points}
是因为在深度嵌套的对象中,内部对象也将是新对象。
推荐阅读
- python-3.x - 循环和数据帧的困难
- javascript - Filter Javascript array and return only objects that have a populated key
- android - 清单合并失败错误,构建失败
- angular - Angular 7 ng new 错误:Schematic input does not validate against Schema: {"name":"test"} 错误:数据路径“”应该有
- python - 如何在 ipython 控制台中定义类输出
- c++ - 如何将 MPI_Datatypes 传递给 C/C++ 中的函数?
- python - Python:如何显示数据框中的数据行,然后再次提示用户输入下一批行
- html - 如何使用引导程序对齐左侧的按钮和同一行中心的徽标?
- c# - 在 C# 中动态创建锯齿状数组的问题
- gcc - gcc ARM 产生不正确的代码 - 如何更正