使用 React 钩子将 setState 传递给子组件 [英] Passing setState to child component using React hooks
问题描述
我很好奇将 setState
作为道具传递给子组件(哑组件)是否违反了任何最佳实践"或会影响优化.
I'm curious if passing setState
as a prop to a child (dumb component) is violating any "best practices" or will affect optimization.
这是一个示例,我让父容器将 state
和 setState
传递给两个子组件,其中子组件将调用 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.
我没有在子进程中显式调用 setState
,它们引用了一个服务来处理状态属性的正确设置.
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>
)
}
仪表板 setState 服务示例
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.
推荐答案
可以从子进程调用一个函数来设置父进程的状态,但是在执行此操作时需要记住一些事项
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) 从纯粹的语法角度来看,我希望您实际上不会将函数称为setState",因为您通常不希望这样做
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) 意识到从子级内部调用函数时,您正在影响父级而不是子级的状态.如果您不知道您打算操作哪些数据以及从何处操作,这可能会导致一些奇怪的结果.
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.
这篇关于使用 React 钩子将 setState 传递给子组件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!