30秒学会 React 片段 – useAsync
A hook that handles asynchronous calls.
- Create a custom hook that takes a handler function,
fn
. - Define a reducer function and an initial state for the custom hook’s state.
- Use the
React.useReducer()
hook to initialize thestate
variable and thedispatch
function. - Define a
run
function that will run the provided callback,fn
, while usingdispatch
to updatestate
as necessary. - Return an object containting the the properties of
state
(value
,error
andloading
) and therun
function.
继续阅读 30秒学会 React 片段 – useAsync