Recently, I have been following the project to learn from hooks. I have changed the old project into the new one, and I am also learning bit by bit.

The problem is that while using hooks, you want to modify the state data before executing the logic of the request interface API.

As follows:

const [filterParams, setFilterParams] = useState({ cate1Id: 101.pageNum: 1.pageSize: 10 })
// When the child executes the parent's method and passes back an argument, it wants to call the API after state is updated
const onFetch = (params) = > {
    setFilterParams(params)
    fetchList(params)
}

const fetchItemCodeList = (async (params) = > {    
    setTableLoading(true)    
    const res = awaitfetchListApi({ ... filterParams, ... params }) setTableLoading(false)})Copy the code

This doesn’t work because setFilterParams is asynchronous, resulting in incorrect parameters when requesting the interface.

This.setstate () can be updated by executing a callback, which is equivalent to this.setState() in which hooks execute the set method, but no callback arguments are provided.

So what can be done?

In fact, useEffect can be used to solve this problem. The method is to use the useEffect dependency, so that after the state is updated, the change of the dependency can be monitored and the related logic of useEffect can be automatically executed.

UseEffect (() => {fetchItemCodeList()}, [filterParams]) Const onFetch = (params) => {setFilterParams(params)
    // fetchList(params)
}Copy the code