简体   繁体   English

使用 React hooks 将 setState 传递给子组件

[英]Passing setState to child component using React hooks

I'm curious if passing setState as a prop to a child (dumb component) is violating any "best practices" or will affect optimization.我很好奇将setState作为道具传递给孩子(哑组件)是否违反了任何“最佳实践”或会影响优化。

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.这是一个示例,其中父容器将statesetState传递给两个子组件,其中子组件将调用setState函数。

I do not explicitly call setState in the children, they reference a service to handle the correct setting of state properties.我没有在孩子中明确调用setState ,他们引用一个服务来处理状态属性的正确设置。

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仪表板 setState 服务示例

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.到目前为止,我还没有注意到任何状态问题。

A good practice would encompass you creating a handler function which delegates to the setState function and passing this function to the child component.一个好的做法是创建一个处理函数,该函数委托给setState函数并将该函数传递给子组件。

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 1)我希望你实际上不是将函数称为“setState”,因为通常你不希望这样做,从纯粹的语法角度来看

2) Realize that you are affecting the state of the parent and not the child when calling the function from within the child. 2) 意识到在从子对象中调用函数时,您影响的是父对象的状态,而不是子对象的状态。 This could lead to some funky results if you lose track of what data you are intending to manipulate and from where.如果您忘记了要操作的数据以及从何处操作,这可能会导致一些奇怪的结果。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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