Lifting State
Svarbu:
- jeigu state yra vaikiname tai uzmount dings ir state
- jeigu tstae teviniame, tai jam pasiekitus bus perrenderinti vaikai
import { useState } from 'react' function App() { return ( <div> <Counter /> </div> } } function Counter() { const [count, setCount] = useState(0) return ( <div> <button onClick={() => setCount(count + 1}> Increase </button> </div> ) }
Jeigu dviems vaikams reikia state reikia jį iškelti aukščiau. T. y. į tėvini komponwentą ir perduoti vaikams.
function App() { return ( <div> <Counter /> <CountDisplay /> </div> } } function CountDisplay() { return <div>Count: 0</div> }
Iškeliam state į App komponentą
function App() { const [count, setCount] = useState(0) return ( <div> <Counter count = {count} setCount = { setCount} /> <CountDisplay count={count} /> </div> }
Colocate state
Iš parent komponento state iškeliame į child. Viskas kas buvo ti atskirai:
Kita
filtracijos pvzd (nesusija su tema)
isFavorited={favorites.includes(post.id)}- PASIEMAME ID TEVINIAME NES TEN NAUDOJAME (VAIKUI NESIUNCIAM)
matchinProps.sort((a, b) = => { const aFav = favorites.includes(a.id) const bFav = favorites.includes (b.id) return aFav === bFav ? 0: aFav ? -1 : 1 }) .map(post => ( <Card key={post.id} post={post} isFavorited={favorites.includes(post.id)} onFavoriteClick= {favorite => { setFavorites (prevFavorites => { if (favorite) { return [...prevFavorites, post.id] } else { return prevFavorites.filter(id => id } }) ))}