在React中使用useState不能在功能组件中更新状态

时间:2020-03-20 12:43:24

标签: javascript reactjs

我正在尝试在state中更新function component

似乎我在这里遇到问题。请说出为什么会出错?

代码段:

import React, { useState, useEffect } from 'react';

const HomeFunctional = () => {

  const [details, setDetails] = useState({name: "Jack Rogers", age: 29, city: "New York"});

  alpha = () => {
    setDetails({name: "Julious Cezer", age: 59, city: "Rome"});
  }

  return (
    <div>
      <p>Home Functional!</p>
      <p>{details.name + "/" + details.age + "/" + details.city} </p>
      <button onClick={this.alpha}>Change Values</button>
    </div>
  )
}

export default HomeFunctional;

错误:

enter image description here

1 个答案:

答案 0 :(得分:3)

如果您使用的是功能组件,则必须编写const alpha

 const alpha = () => {

而不是使用this.alpha,您只需编写alpha

 <button onClick={alpha}>Change Values</button>

CodeSandbox here