Skip to content

Instantly share code, notes, and snippets.

@chrisryana
Last active August 22, 2020 07:42
Show Gist options
  • Save chrisryana/c5d2a4373ddff08b16b6cdfe1b817f17 to your computer and use it in GitHub Desktop.
Save chrisryana/c5d2a4373ddff08b16b6cdfe1b817f17 to your computer and use it in GitHub Desktop.
Как в функциональном компоненте сохранить предыдущее значение state
function NamesList() {
const [names, setNames] = React.useState(['bob'])
const prevNamesRef = React.useRef([])
React.useEffect(() => {
prevNamesRef.current = names
})
const prevNames = prevNamesRef.current
return (
<div>
<h4>Current names:</h4>
<ul>
{names.map((name) => (
<li key={name}>{name}</li>
))}
</ul>
<h4>Previous names:</h4>
<ul>
{prevNames.map((prevName) => (
<li key={prevName}>{prevName}</li>
))}
</ul>
</div>
)
}
// аналог componentDidMount
import React from 'react'
import axios from 'axios'
function MyComponent() {
const [frogs, setFrogs] = React.useState([])
const [error, setError] = React.useState(null)
const mounted = React.useRef(false)
async function fetchFrogs(params) {
try {
const response = await axios.get('https://some-frogs-api.com/v1/', {
params,
})
if (mounted.current) {
setFrogs(response.data.items)
}
} catch (error) {
if (mounted.current) {
setError(error)
}
}
}
React.useEffect(() => {
mounted.current = true
return function cleanup() {
mounted.current = false
}
}, [])
return (
<div>
<h4>Frogs:</h4>
<ul>
{this.state.frogs.map((frog) => (
<li key={frog.name}>{frog.name}</li>
))}
</ul>
</div>
)
}
// Это работает потому что React.useEffect запускается после того, как компонент отрендерился
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment