我正在尝试在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;
错误:
答案 0 :(得分:3)
如果您使用的是功能组件,则必须编写const alpha
const alpha = () => {
而不是使用this.alpha
,您只需编写alpha
。
<button onClick={alpha}>Change Values</button>
CodeSandbox here