function useEffect(effect: EffectCallback, deps?: DependencyList): void;
type EffectCallback = () => (void | Destructor);
type Destructor = () => void;
type DependencyList = ReadonlyArray<unknown>;
注意:由于EffectCallbackk
只能返回空或者Destroctor
,这也就意味着他不能是async函数,因为async函数意味着返回值是个promise。如果要在useEffect中调用异步函数,使用下面的方法:
React.useEffect(() => {
doSomeAsyncThing().then(result => {
// do something with the result
})
})
local storage的综合案例
import * as React from 'react'
function useLocalStorageState(
key,
defaultValue = '',
// the = {} fixes the error we would get from destructuring when no argument was passed
// Check https://jacobparis.com/blog/destructure-arguments for a detailed explanation
{serialize = JSON.stringify, deserialize = JSON.parse} = {},
) {
const [state, setState] = React.useState(() => {
const valueInLocalStorage = window.localStorage.getItem(key)
if (valueInLocalStorage) {
// the try/catch is here in case the localStorage value was set before
// we had the serialization in place (like we do in previous extra credits)
try {
return deserialize(valueInLocalStorage)
} catch (error) {
window.localStorage.removeItem(key)
}
}
return typeof defaultValue === 'function' ? defaultValue() : defaultValue
})
const prevKeyRef = React.useRef(key)
// Check the example at src/examples/local-state-key-change.js to visualize a key change
React.useEffect(() => {
const prevKey = prevKeyRef.current
if (prevKey !== key) {
window.localStorage.removeItem(prevKey)
}
prevKeyRef.current = key
window.localStorage.setItem(key, serialize(state))
}, [key, state, serialize])
return [state, setState]
}
function Greeting({initialName = ''}) {
const [name, setName] = useLocalStorageState('name', initialName)
function handleChange(event) {
setName(event.target.value)
}
return (
<div>
<form>
<label htmlFor="name">Name: </label>
<input value={name} onChange={handleChange} id="name" />
</form>
{name ? <strong>Hello {name}</strong> : 'Please type your name'}
</div>
)
}
function App() {
return <Greeting />
}
export default App