简体   繁体   中英

reactjs: how to update the child state when parent props are updated

I update the parentcomponent from child component and in return i get the new props from parent, and then i want the child state to get updated based on the prop.

    export default function ParentCompnent(){
        [name,setName] = useState("test")

        function setNameMod(){
            setName(some random name)
        }
        render(
            <>
            <ChildComponent name=name setNameMod=setNameMod />
            </>
        )

    }


    function ChildComponent(props){
        {name,setNameMod} = props
        [steps,setSteps] = useState(getSteps(name))
        getSteps(name){
            .....
            return some_array
        }

        function refreshSteps(){
            setNameMod()

            setSteps(getSteps(name))
            // i am expecting new name from parent be used here
            // but it looks the old name is being used.
        }

        render(
            <>
            <button onclick={()=>refreshSteps()}>Refresh</button>
            steps.map(....)
            </>


            )
    }

I can put the steps in parent and pass as props. but i want to keep the logic at one place

Now can i do this

Try setSteps() inside useEffect() . It should work like ComponentDidUpdate() for Class Components. In useEffect we should send the parameter for a change in which our state should get updated. So whenever name will be updated the reflection will be on setSteps().

useEffect(()=> setSteps(getSteps(name)), [name]);

To update child component when props get updated, you have to use useEffect hook. You can add hook in your ChildComponent:

useEffect(() => {
   setSteps(getSteps(name));
}, [name]);

You should also set initially steps to empty array to avoid calling getSteps repetitively.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM