使用useState时如何更改对象中的值

时间:2019-12-14 14:56:33

标签: javascript reactjs

到目前为止,我正在学习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

4 个答案:

答案 0 :(得分:0)

只需简单地在vote函数中首先使用传播语法克隆原始对象,这样做您将获得一个名为newPoints的新对象。然后,您需要通过添加newPoints[selected] + 1来增加投票数来更新所选投票。然后可以使用setPoints进行更新了。

类似这样的东西:

const [selected, setSelected] = useState(0);

const vote = () => {
   const newPoints = {...points};
   newPoints[selected] = newPoints[selected] + 1;
   setPoints(newPoints);
}

在此处进一步阅读:Spread syntax

希望对您有帮助!

答案 1 :(得分:0)

这应该可以解决问题。

function vote() {
    let p = {...points};
    p[selected] += 1;
    setPoints(p);
    console.log( points);
  }

答案 2 :(得分:0)

  1. 我认为每个人都想念的最重要的事情是

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

    如果您根据先前的值设置了状态,则需要传递一个 setState的函数以避免出现种族冲突。

  2. 如果状态是一个对象,则无需使用对其进行突变,因为该引用将是相同的旧对象,并且react不会重新呈现。

    一般来说,要解决此问题,我要做的是

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

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

答案 3 :(得分:-1)