英文:
How to listen to changes in instance of a class object in React?
问题
I'm here to provide translations. Here's the translation of your text:
"你好吗?
我试图监听 React 应用中的一个 Class 对象实例的更改。我可以看到类的值发生了变化,但我无法让 useEffect 监听这些变化!
这个类本身非常简单:
class Person {
constructor(name) {
this.name = name;
this.hunger = 0;
}
increaseHunger() {
this.hunger += 10;
}
}
export default Person;
然后我有我的 React 应用组件:
import React from "react";
import Person from "./classes/Person";
export default function App() {
const [person, setPerson] = React.useState(new Person("John"));
React.useEffect(() => {
console.log("Effect");
}, [person.hunger]);
return (
<div>
<div>{person.name}</div>
<div>{person.hunger}</div>
<button onClick={() => person.increaseHunger()}>Click</button>
</div>
);
}
每当我点击按钮时,我可以看到类函数内部的日志,我也可以看到饥饿值发生变化,但 useEffect 函数中的日志从未触发。我认为可能是 React 组件中的 person 对象的引用没有发生变化,但我无法弄清楚为什么!
有没有人知道我可能做错了什么?"
英文:
how are you?
I'm trying to listen to the changes in an instance of a Class object in a React App. I can see that the value of the class changes, but i can't get a useEffect to listen to this changes!
The class itself is pretty simple:
class Person {
constructor(name) {
this.name = name;
this.hunger = 0;
}
increaseHunger() {
this.hunger += 10;
}
}
export default Person;
Then i have my React App component:
import React from "react";
import Person from "./classes/Person";
export default function App() {
const [person, setPerson] = React.useState(new Person("John"));
React.useEffect(() => {
console.log("Effect");
}, [person.hunger]);
return (
<div>
<div>{person.name}</div>
<div>{person.hunger}</div>
<button onClick={() => person.increaseHunger()}>Click</button>
</div>
);
}
Whenever i click the button, i can see the log inside the class functions and i can see that the hunger changes, but the log in the useEffect functions never triggers. I think that perhaps the reference of the person object in the React component is not changing, but i can't figure out why!
Does anyone knows what i'm may be doing wrong?
答案1
得分: 2
你需要更新状态,这样你的 person.hunger 才能触发并执行你的 useEffect。
const handleChange = () => {
setPerson((prev) => {
return { ...prev, hunger: person.hunger + 10 };
});
};
请查看 LIVE DEMO。
英文:
You need to update the state so your person.hunger can be trigger and execute your useEffect .
const handleChange = () => {
setPerson((prev) => {
return { ...prev, hunger: person.hunger + 10 };
});
};
Please see LIVE DEMO
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论