xml ui - effect
useEffect
accepts a function which can perform any side effects.
useEffect(effectFunction, arrayDependencies)
每次绘制都执行
Without an array dependency, the effect function will be run after every single render.
useEffect(() => {
console.log("This will be logged after every render!")
})
() => {
const [age, setAge] = useState(0)
const handleClick = () => setAge(age + 1)
useEffect(() => {
document.title = 'You are ' + age + ' years old!'
})
return <div>
<p> Look at the title of the current tab in your browser </p>
<button onClick={handleClick}>Update Title!! </button>
</div>
}
effectFunction返回函数,被返回的函数会在unmount前调用
() => {
useEffect(() => {
const clicked = () => console.log('window clicked')
window.addEventListener('click', clicked)
// return a clean-up function
return () => {
window.removeEventListener('click', clicked)
}
}, [])
return <div>
When you click the window you'll
find a message logged to the console
</div>
}
() => {
//只在mount时候调用一次
useEffect(() => {
const clicked = () => console.log('window clicked')
window.addEventListener('click', clicked)
return () => {
window.removeEventListener('click', clicked)
}
}, [])
//每次重绘都调用
useEffect(() => {
console.log("another useEffect call");
})
return <div>
Check your console logs
</div>
}
条件触发effect
() => {
const [randomNumber, setRandomNumber] = useState(0)
const [effectLogs, setEffectLogs] = useState([])
useEffect(
() => {
setEffectLogs(prevEffectLogs => [...prevEffectLogs, 'effect fn has been invoked'])
},
[randomNumber]
)
return (
<div>
<h1>{randomNumber}</h1>
<button
onClick={() => {
setRandomNumber(Math.random())
}}
>
Generate random number!
</button>
<div>
{effectLogs.map((effect, index) => (
<div key={index}>{'🍔'.repeat(index) + effect}</div>
))}
</div>
</div>
)
}
仅mount时候触发
() => {
const [randomNumber, setRandomNumber] = useState(0)
const [effectLogs, setEffectLogs] = useState([])
// the effect function will be called only on mount
useEffect(
() => {
setEffectLogs(prevEffectLogs => [...prevEffectLogs, 'effect fn has been invoked'])
},
[]
)
return (
<div>
<h1>{randomNumber}</h1>
<button
onClick={() => {
setRandomNumber(Math.random())
}}
>
Generate random number!
</button>
<div>
{effectLogs.map((effect, index) => (
<div key={index}>{'🍔'.repeat(index) + effect}</div>
))}
</div>
</div>
)
}