简体   繁体   English

React Hooks Onchange 同步

[英]React Hooks Onchange Synchronize

Im passing my app from the class model to the hooks and in my code y have a dropdown list that when executes the onChange method it does this:我将我的应用程序从类模型传递给钩子,在我的代码中,我有一个下拉列表,当执行 onChange 方法时,它会执行以下操作:

filter(event)
{
    this.setState({
        selectedFilter: event.target.value
      },() => { this.chargeInfo(); });
}

In my class model works perfectly, but i dont know how to do this with the hooks, im passing the method chargeInfo() and the variable selectedFilter by the props because this component is a child, so what I have is this code:在我的类模型中工作完美,但我不知道如何使用钩子来做到这一点,我通过道具传递了方法 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
}

How can I adapt this in a Sync mode that execute first the props.changeSelectedFilter and later the props.chargeInfo?.我怎样才能在同步模式下适应这个,首先执行 props.changeSelectedFilter 然后执行 props.chargeInfo?。

You may need to use the State Hook like this:您可能需要像这样使用 State Hook:

// setting up the default dropdown value
const [dropdownValue, setDropdownValue] = useState('Some Value');

// later, setting a new dropdown value
setDropdownValue('New Value')

See https://reactjs.org/docs/hooks-state.html for more info有关更多信息,请参阅https://reactjs.org/docs/hooks-state.html

I solved using useEffect:我使用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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM