如何在useState挂钩之后立即执行功能?

时间:2019-11-22 21:27:49

标签: reactjs react-hooks

在类组件中,我可以执行以下操作:

this.setState({loading: true}, () => console.log('state updated'));

使用useState的功能组件中有什么等效功能?

3 个答案:

答案 0 :(得分:2)

如果您还有其他逻辑要在设置状态后执行 ,则通常将其包装在特定于要执行的动作的处理函数中:

import React, { useState } from 'react'

const Component = () => {
  const [loading, setLoading] = useState(false)

  const handleLoading = () => {
    setLoading(true);
    console.log('state updated');
  }

   return <button onClick={handleLoading}>Click Me</button>;
}

注意:如下面的@Federkun所述,这不会为您提供刚刚设置的状态,因为该组件尚未重新渲染。

答案 1 :(得分:1)

我假设您可以为此目的从useEffect挂钩中受益。您可以在下面的the official React manual.

中找到一个示例
import React, { useState, useEffect } from 'react';

function Example() {
  const [count, setCount] = useState(0);

  // Similar to componentDidMount and componentDidUpdate:
  useEffect(() => {
    // Update the document title using the browser API
    document.title = `You clicked ${count} times`;
  });

  return (
    <div>
      <p>You clicked {count} times</p>
      <button onClick={() => setCount(count + 1)}>
        Click me
      </button>
    </div>
  );
}

答案 2 :(得分:0)

发现正确的方法是使用前面提到的useEffect挂钩,然后将我们正在侦听的状态(在本例中为count)作为参数传递


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

function Example() {
  const [count, setCount] = useState(0);

  function onCountChange(){
    console.log('count has changed to', count);
  }
  // this will run every time count changes,
  useEffect(() => {
    // function that we want to run on ever change of count
    onCountChange()
  }, [count]);

  return (
    <div>
      <p>You clicked {count} times</p>
      <button onClick={() => setCount(count + 1)}>
        Click me
      </button>
    </div>
  );
}