When I update the state of a parent component from within multiple instances of a child component, I can only see the final update of the state in the parent component. I want to be able to get every single update of the state in the parent component.
Here is my parent component:
import React from 'react' import TestChild from './TestChild' export default function Parent () { const [state, setState] = React.useState(null) React.useEffect(() => { console.log('Parent state:', state) }, [state]) function renderChildren() { const dataArray = [1, 2, 3] return ( dataArray.map((value, index) => { return ( <TestChild key={index} value={value} setParentState={setState} /> ) }) ) } return ( <> {renderChildren()} </> ) }
and this is the child component:
import React from 'react' export default function Child (props) { React.useEffect(() => { console.log(`Child ${props.value} useEffect executed`) props.setParentState(currentState => { return ({ ...currentState, [props.value]: props.value }) }) }, []) return ( <> </> ) }
This is the console log:
Child 1 useEffect executed Child 2 useEffect executed Child 3 useEffect executed Parent state: null Parent state: Object { 1: 1, 2: 2, 3: 3 }
What I'm trying to achieve is this:
Parent state: null Child 1 useEffect executed Parent state: Object { 1: 1 } Child 2 useEffect executed Parent state: Object { 1: 1, 2: 2 } Child 3 useEffect executed Parent state: Object { 1: 1, 2: 2, 3: 3 }
https://stackoverflow.com/questions/66937432/how-to-lift-up-the-state-in-function-component-with-granular-control-over-the-st April 04, 2021 at 10:06AM
没有评论:
发表评论