首页 > 解决方案 > 使用 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);

谢谢你。

链接:https ://codesandbox.io/s/react-b6-usestate-type-2-05q8x

标签: javascriptreactjs

解决方案


  1. 我认为这里每个人都缺少的最重要的是

    setPoints( points => {
        //new Points 
        return newPoints})
    

    如果您从以前的值设置状态,那么您需要为 setState 传递一个函数以避免竞争情况。

  2. 如果 state 是一个对象,那么改变它就没有用处,因为引用将是相同的旧引用并且 react 不会重新渲染。

    为了解决这个问题,我通常做的是

    setPoints( points => {
        let newPoints = JSON.parse(JSON.stringify(points));
        //change newPoints; 
        return newPoints
    })
    

    我选择JSON.parse(JSON.stringiy(points))rathar的主要原因{...points}是因为在深度嵌套的对象中,内部对象也将是新对象。


推荐阅读