简体   繁体   English

一般而言,使用 React 的 Context 和步骤的表单是一个好主意吗?

[英]Is using a React's Context for form with steps a good idea in general?

If I have a form with a couple of steps, should I use Context API or state inside of the parent component?如果我有一个包含几个步骤的表单,我应该在父组件内部使用 Context API 或 state 吗?

The only difference between Context API vs "state in the parent component" is how many levels you have to pass down props (the Provider in context is "state in an ancestor component" rather than a parent component).上下文 API 与“父组件中的状态”之间的唯一区别是您必须传递多少级别的道具(上下文中的 Provider 是“祖先组件中的状态”而不是父组件)。

So it depends on your component structure.所以这取决于你的组件结构。 If you have to pass down a callback prop more than one level, I'd go with context.如果你必须传递一个以上的回调道具,我会 go 与上下文。

EDIT: With reference to a comment - your own personal preference comes in play with how far you are willing to prop drill for simple state vs context.编辑:参考评论 - 您自己的个人偏好与您愿意为简单的 state 与上下文进行多远的钻头有关。 I don't like doing it more than one level.我不喜欢超过一个层次。 In my opinion (that's a big IMO), it mixes the concerns of a component - you'll end up making a component accept props for the sole purpose of passing them on to child components.在我看来(这是一个很大的 IMO),它混合了组件的关注点 - 您最终会让组件接受道具,其唯一目的是将它们传递给子组件。

It's a good question.这是个好问题。 It depends on your purposes.这取决于你的目的。 So, for state management you can use context/ref/state/or library based on FLAX pattern.因此,对于 state 管理,您可以使用基于 FLAX 模式的上下文/参考/状态/或库。

I prefer to use context in a lot of situations.我更喜欢在很多情况下使用上下文。 If you want to avoid props drilling then the best solution is to use context/ref, but if you have to rerender all your steps then context isn't suitable for you.如果您想避免道具钻探,那么最好的解决方案是使用 context/ref,但如果您必须重新渲染所有步骤,那么 context 不适合您。

Here you can understand all benefits of using context在这里您可以了解使用上下文的所有好处

https://daveceddia.com/context-api-vs-redux/ https://daveceddia.com/context-api-vs-redux/

That depends a lot, but I honestly prefer in this use case to use it as state in the parent.这取决于很多,但老实说,在这个用例中,我更喜欢在父级中将其用作 state。

Context API, as it says in documentation, was designed for "global" share of data between a tree of react components.上下文 API,正如它在文档中所说的那样,是为 React 组件树之间的“全局”数据共享而设计的。 I don't think you should create context just to avoid passing props through components.我认为您不应该仅仅为了避免通过组件传递道具而创建上下文。 I'd prefer to rethink component structure to make it possible to do less props drilling.我更愿意重新考虑组件结构,以减少道具钻孔。

Those two blogs from Kent C.这两个来自肯特 C 的博客。 Dodds helped me a lot:多兹帮了我很多忙:

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

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