gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-04 15:10:47 25 4
gpt4 key购买 nike

我想在触发正常函数 (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的更新值。您应该通过添加依赖项 filterConsultantIduseEffect 中获取它。

useEffect(() => {
console.log(filterConsultantId);
}, [filterConsultantId]);

关于reactjs - useState 函数在功能组件中不起作用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/65247567/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com