最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - How React listens for state changes - Stack Overflow

programmeradmin2浏览0评论

I currently have started learning React.js and I wonder how React listens for state changes?

I mean I know there is not any event listeners in Javascript for tracking variable change and I'm pretty sure that we can not listen for changing a variable (without using an interval to check the change) in Javascript natively...

But in React if you change a property of a state it will finds out the change instantly?!

How it's implemented in React?

I currently have started learning React.js and I wonder how React listens for state changes?

I mean I know there is not any event listeners in Javascript for tracking variable change and I'm pretty sure that we can not listen for changing a variable (without using an interval to check the change) in Javascript natively...

But in React if you change a property of a state it will finds out the change instantly?!

How it's implemented in React?

Share Improve this question asked Dec 24, 2020 at 21:39 user13849624user13849624 3
  • Have a read of something like w3schools./react/react_state.asp and let us know if you're still puzzled.. (And also if you're using redux, let us know) – Caius Jard Commented Dec 24, 2020 at 21:44
  • '>- no event listeners.. for tracking variables' - not entirely true, there's such thing as Proxy – Yevhen Horbunkov Commented Dec 24, 2020 at 21:51
  • 1 Such function like setState only update the state and call the ponent again with new state value. Dan Abramov has a good explanation for this – kunquan Commented Dec 24, 2020 at 21:54
Add a ment  | 

1 Answer 1

Reset to default 5

React does not passively listen for state changes at all. The only way it knows the state changed is because you explicitly tell react to change the state. In class ponents, that's done with this.setState:

class Example extends React.Component {
  state = {
    name: 'valentina';
  }

  ponentDidMount() {
    setTimeout(() => {
      this.setState({ name: 'jebediah' });
    }, 1000);
  }

  // ...
}

In a function ponent, that's with the state-setter function returned by useState:

const Example = (props) => {
  const [name, setName] = useState('valentina');

  useEffect(() => {
    setTimeout(() => {
      setName('jebediah');
    }, 1000);
  }, []);

  // ...
}
发布评论

评论列表(0)

  1. 暂无评论