useState 函数在功能组件中不起作用

useState function is not working in functional component

我想在触发正常函数 (handleConsultantChange) 后使用 useState 函数 (setFilterConsultantId) 更改状态 (filterConsultantId),并且我希望状态值发生更改当我在另一个正常函数 (getActiveLeads) 中使用该状态时。但是状态没有改变。请在下面查看我的 React 功能组件:

const TabActiveLeads = ({
    ...
}) => {
    const [filterConsultantId, setFilterConsultantId] = useState('');   
    
    //after this arrow function triggered, 
    const handleConsultantChange = (event) => {
        setFilterConsultantId(event.target.value); //and the filterConsultantId should be changed here
        
        //this getActiveLeads function is called
        getActiveLeads();
    };
    
    const getActiveLeads = () => {
        
        // but the filterConsultantId here is not changed after it should be changed inside handleConsultantChange function
        console.log(filterConsultantId);
    }; 
};

export default TabActiveLeads;

我不明白,为什么filterConsultantIdgetActiveLeads函数内部没有改变?以前它应该通过在 handleConsultantChange 函数中调用 setFilterConsultantId 来更改。

感谢您的帮助..

setFilterConsultantId是异步方法,所以不能在setFilterConsultantId之后立即获取filterConsultantId的更新值。 您应该通过添加依赖项 filterConsultantId.

将其放入 useEffect
useEffect(() => {
  console.log(filterConsultantId);
}, [filterConsultantId]);