Passing setState to child component using React hooks

余生颓废 提交于 2020-08-08 05:50:10

问题


I'm curious if passing setState as a prop to a child (dumb component) is violating any "best practices" or will affect optimization.

Here is an example where I have the parent container passing state and setState to two child components, where the child components will call the setState function.

I do not explicitly call setState in the children, they reference a service to handle the correct setting of state properties.

export default function Dashboard() {

    const [state, setState] = useState({
        events: {},
        filters: [],
        allEvents: [],
        historical: false,
    });


    return (
        <Grid>
            <Row>
                <Col>
                    <EventsFilter
                        state={state}
                        setState={setState}
                    />
                    <EventsTable
                        state={state}
                        setState={setState}
                    />
                </Col>
            </Row>
        </Grid>
    )
}

Example of dashboard setState service

function actions(setState) {
    const set = setState;
    return function () {
        return ({

            setEvents: (events) => set((prev) => ({
                ...prev,
                events,
            })),

            setAllEvents: (allEvents) => set((prev) => ({
                ...prev,
                allEvents,
            })),

            setFilters: (name, value) => set((prev) =>
                ({
                    ...prev,
                    filters
                })
            ),
        })
    }
}

So far I haven't noticed any state issues.


回答1:


It is ok to call a function from the child to set the state of the parent, however there is a couple things to keep in mind when doing this

1) I hope you aren't actually calling the function as "setState" as generally you don't want to this, from a purely syntactical standpoint

2) Realize that you are affecting the state of the parent and not the child when calling the function from within the child. This could lead to some funky results if you lose track of what data you are intending to manipulate and from where.




回答2:


A good practice would encompass you creating a handler function which delegates to the setState function and passing this function to the child component.




回答3:


You can use a funcion to wrap this setState. It's not a good practice to pass it to a child. Just update it on the component.

<Child 
updatestate={(childInfo) => {
  setState(childInfo);
}}
/>


来源:https://stackoverflow.com/questions/59850845/passing-setstate-to-child-component-using-react-hooks

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!