在React中-useState不起作用并且不更新状态

时间:2019-07-24 03:08:54

标签: reactjs

下面添加了示例代码段,

从'react'导入React,{useState};

function Example() {
  const [state, setState] = useState({counter:0});
  const add1ToCounter = () => {
    const newCounterValue = state.counter + 1;
    setState({ counter: newCounterValue});
  }

  return (
    <div>
      <p>You clicked {state.Counter} times</p>
      <button onClick={add1ToCounter}>
        Click me
      </button>
    </div>
  );
}

2 个答案:

答案 0 :(得分:0)

您应该引用“ state.counter”-小写字母

<p>You clicked {state.counter} times</p>

答案 1 :(得分:0)

您犯了一些错误。 只需将它们替换为下面的行:
实际上,您只写了“ state.Counter” 而不是“ state.counter”

function Example() {
  const [state, setState] = useState({counter:0});
  const add1ToCounter = () => {
    const newCounterValue = state.counter + 1;
    setState({ counter: newCounterValue});
  }

  return (
    <div>
      <p>You clicked {state.counter} times</p>
      <button onClick={add1ToCounter}>
        Click me
      </button>
    </div>
  );
}