在使用 redux 时你应该使用 this.setState() 吗? [英] Should you ever use this.setState() when using redux?

查看:33
本文介绍了在使用 redux 时你应该使用 this.setState() 吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在使用 redux 时你应该使用 this.setState() 吗?还是应该一直在调度动作并依靠道具?

Should you ever use this.setState() when using redux? Or should you always be dispatching actions and relying on props?

推荐答案

setState 的明确用途是用于具有本地显示状态但与全局应用程序无关的 UI 组件.例如,表示特定下拉菜单是否主动显示的布尔值不需要处于全局状态,因此更方便地由菜单组件的状态控制.

Clear uses of setState would be for UI components that have local display state, but aren't relevant for the global application. For example a boolean that represents whether a specific dropdown menu is actively displayed doesn't need to be in global state, so it's more conveniently controlled by the menu component's state.

其他示例可能包括层次结构的手风琴显示中线条的折叠/展开状态.或者可能是选项卡导航中当前选择的选项卡.但是,在这两个示例中,您仍然可以选择全局处理 UI 状态.例如,如果您想在浏览器存储中保留展开/折叠状态,以便通过页面刷新保留它,这将是必要的.

Other examples might include the collapse/expand state of lines in an accordion display of a hierarchy. Or possibly the currently selected tab in tab navigation. However in both of these examples you might still choose to handle UI state globally. For example this would be necessary if you wanted to persist the expand/collapse state in browser storage so that it would be preserved by page refresh.

在实践中,通常最容易使用本地状态实现此类 UI 元素,并根据需要将它们重构为全局状态.

In practice it's usually easiest to implement such UI elements with local state, and refactor them into global state as needed.

这篇关于在使用 redux 时你应该使用 this.setState() 吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆