我无法使用钩子更新状态

时间:2020-01-14 00:31:03

标签: javascript reactjs

您好,我正在尝试通过onClick事件来更新我的状态。 onClick执行但无法更新状态。

import React, { useState } from "react";
import logo from "./logo.svg";
import "./App.css";

function App() {
  const [sixBreaks, setSixTotal] = useState({
    breaks: 11,
    screen: 15,
    hindge: 5
  });
  const update = () => {
    return setSixTotal(sixBreaks.breaks + 1)
  }
  return (
    <div className="App">
      <h1>Total Broken: {sixBreaks.breaks}</h1>
      <button onClick={() => update()}>
        CLICK ME TO INCREMENT
      </button>
    </div>
  );
}

export default App;



3 个答案:

答案 0 :(得分:2)

sixBreaks是一个对象,您必须更新整个对象才能更新breaks状态。

const update = () => {
  setSixTotal({ 
    ...sixBreaks, 
    breaks: sixBreaks.breaks + 1 
  });
};

执行setSixTotal(sixBreaks.breaks + 1)不会适当地更新您的breaks状态,因为这意味着您正在用state键的值覆盖breaks

答案 1 :(得分:0)

使用传播运算符更新以更新对象属性上的值。进一步了解DCG

const update = () => {
    return setSixTotal({...sixBreaks, {breaks: sixBreaks.breaks + 1}})
}

或使用如下的Object.assign函数:

const update = () => {
        const updatedValue = Object.assign({}, sixBreaks, {breaks: sixBreaks.breaks + 1})
        return setSixTotal(updatedValue)
    }

所以像这样更新您的代码:

import React, { useState } from "react";
    import logo from "./logo.svg";
    import "./App.css";

    function App() {
      const [sixBreaks, setSixTotal] = useState({
        breaks: 11,
        screen: 15,
        hindge: 5
      });
      const update = () => {
        setSixTotal({...sixBreaks, {breaks: sixBreaks.breaks + 1}})
      }
      return (
        <div className="App">
          <h1>Total Broken: {sixBreaks.breaks}</h1>
          <button onClick={() => update()}>
            CLICK ME TO INCREMENT
          </button>
        </div>
      );
    }

    export default App;

答案 2 :(得分:0)

你应该做的


const update = () => {
  return setSixTotal(prev => ({
    ...prev,
    breaks: prev.breaks + 1
  }));
};

不要直接使用sixBreaks.breaks,因为React不能保证在更新时会保持一致,而是使用我上面写的回调样式来避免错误