简体   繁体   中英

In React / Redux, if a function component is dispatching a function using redux-thunk, how can it setIsLoading()?

I think the reason we use redux-thunk is so that we can dispatch a function when we define mapDispatchToProps() . (Usually, by having actionCreator() returning a function)

But, assuming we are using a function component, when we dispatch a function to load data, there seems to be no way to use the setIsLoading() which comes from

const [isLoading, setIsLoading] = useState(false);

because setIsLoading is inside the function component and you can't use it in mapDispatchToProps() ?

It seems one way is to use

<button onClick={() => {setIsLoading(true); props.dispatchGetData(setIsLoading)}}>

which is first setIsLoading(true) and pass the setIsLoading to dispatchGetData() so that later on, it can call setIsLoading(false) when data is received or failed to received.

Is this a proper way or what is a proper way? It seems we can also use useEffect() and we can directly do the fetch() and won't dispatch any function and therefore, not using redux-thunk?

You can useEffect and check if the data come back to the component has changed.

Something like this:

useEffect(() => { 
    setIsLoading(false);
}, [props.data])

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