[英]React Hooks Onchange Synchronize
我将我的应用程序从类模型传递给钩子,在我的代码中,我有一个下拉列表,当执行 onChange 方法时,它会执行以下操作:
filter(event)
{
this.setState({
selectedFilter: event.target.value
},() => { this.chargeInfo(); });
}
在我的类模型中工作完美,但我不知道如何使用钩子来做到这一点,我通过道具传递了方法 chargeInfo() 和变量 selectedFilter 因为这个组件是一个孩子,所以我有的是这个代码:
<Dropdown onChange={onChangeDropdown} />
const onChangeDropdown = function(event)
{
props.changeSelectedFilter(event.target.value);//this do setSelecedFilter in the parent
props.chargeInfo();//this is the method of the parent that do something
}
我怎样才能在同步模式下适应这个,首先执行 props.changeSelectedFilter 然后执行 props.chargeInfo?。
您可能需要像这样使用 State Hook:
// setting up the default dropdown value
const [dropdownValue, setDropdownValue] = useState('Some Value');
// later, setting a new dropdown value
setDropdownValue('New Value')
我使用useEffect解决了:
useEffect(
() => {
// eslint-disable-next-line react-hooks/exhaustive-deps
props.chargeInfo();}, [props.selectedFilter]
)
const onChangeDropdown = function(event)
{
props.changeSelectedFilter(event.target.value);
}
return(
<Dropdown style={{ marginRight: 10, }} value={props.selectedFilter} options={filters}
onChange={onChangeDropdown} optionLabel="name" placeholder="Filter by" />
)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.