简体   繁体   中英

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:

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:

<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?.

You may need to use the State Hook like this:

// 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

I solved using 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" />
)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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