簡體   English   中英

使用useState時如何更改對象中的值

[英]How to change the value in an object when using 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

只需簡單地在vote函數中首先使用擴展語法克隆原始對象,通過這樣做,您將擁有一個名為newPoints的新對象。 然后您需要通過添加newPoints[selected] + 1來更新選定的一個以增加投票數。 然后就可以用setPoints更新了。

像這樣的東西:

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

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

在此處進一步閱讀: 傳播語法

我希望這有幫助!

這應該可以解決問題。

function vote() {
    let p = {...points};
    p[selected] += 1;
    setPoints(p);
    console.log( points);
  }
  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}的主要原因是因為在深度嵌套的對象中,內部對象也將是新對象。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM