无状态使用React [英] Using React without States

查看:73
本文介绍了无状态使用React的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在构建应用程序的UI,并且正在探索更新UI而不需要使用状态.以下断言是完全正确的吗?

I am building the UI of an app and I am exploring updating the UI without having to use States. Would the following assertion be crudely correct?

'我们不需要状态,因为状态发生变化时,它所做的全部工作就是自动在组件上调用render方法.我们可以通过在相关组件上自己调用render方法来实现相同的实现.

我们仍将实现React的所有相同优势(虚拟DOM,渲染,绘画优化等)'

推荐答案

从技术上讲,您不需要使用React的内部组件状态来构建React应用程序.当然,数据需要保存在某处,因此您需要一种机制,该机制可以在数据更改时将所有数据传递到顶级组件(在该组件中滴入所有其他组件)

It is technically correct that you do not need to use React's internal component state to build a React application. Of course, the data needs to live somewhere, so you need a mechanism which can pass all the data into the top-level component (where it will trickle down into all the other components) when the data changes.

这是通量(以及旨在提供外部反应状态存储的许多其他模式)背后的基本思想.您有一个或多个商店,这些商店在其数据更改时会提供更改事件.然后,这些数据会通过props传递到应用程序中.

This is the basic idea behind flux (and many other patterns designed to provide outside-of-React state storage). You have one or more stores and the stores provide change events when their data changes. Then that data gets passed into the application via props.

function render(data) {
  ReactDOM.render(
    <Application data={data} />,
    containerNode
  )
}

myDataStore.on('change', render);

但是,实际上,由于JavaScript的工作原理,很难做到高效.上面的代码会使每次myDataStore更改时React重新渲染整个组件树,并且如果没有良好的shouldComponentUpdate钩子,这可能是性能问题.使用不可变值有助于更轻松地实现良好的shouldComponentUpdate方法.

In practice, however, it can be difficult to do this performantly because of how JavaScript works. Code like the above would make React re-render the entire component tree each time myDataStore changes, and without good shouldComponentUpdate hooks, this can be a performance issue. Using immutable values helps make it easier to implement good shouldComponentUpdate methods.

您通常会在使用React-of-React数据存储的大型React应用程序中看到以下内容的组合:

What you'll usually see in a larger React application that uses outside-of-React data storage is a combination of:

  • 一个或多个负责获取数据的容器"组件从商店将其传递给他们的孩子.有时,将容器放置在组件树顶部以外的其他位置是有意义的(例如,在一个应用程序中可能有多个容器)
  • 可重用/演示"组件,它们不会挂接到数据存储中,但提供了其他一些好处(例如黑框样式或交互式窗口小部件).在这种情况下,将任何非特定于应用程序的状态保留在组件本身内部通常是有意义的.
  • One or more "container" components that are responsible for getting the data from the stores and passing it to their children. Sometimes it makes sense to put containers somewhere other than the very top of the component tree (e.g. you may have several containers in one app)
  • Reusable/"presentational" components that do not hook into the data store, but provide some other benefit (such as black boxed styles, or an interactive widget). In these cases, it often makes sense to keep any non-application-specific state inside the component itself.

这篇关于无状态使用React的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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