本文介绍了如何在Redux中将全局状态数据处理为深层嵌套组件?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

所以说你有这个组件结构的聊天应用程序:

So say you have a chat aplication with this component structure:

<ChatApp>
  <CurrentUserInfo>...</CurrentUserInfo>
  <ChatsPanel>...</ChatsPanel>
  <SelectedChatPanel>
    <MessagesList>
      <MessageBaloon>
        <MessageText></MessageText>
        <MessageUserHead></MessageUserHead>
      </MessageBaloon>
      ...
    </MessagesList>
  <SelectedChatPanel>
</ChatApp>

和Redux状态如下:

And a Redux state like:

{ 
  currentUser: ...,
  chatsList: ...,
  selectedChatIndex: ...,
  messagesList: [ ... ]
}

如何将当前用户信息提供给< MessageUserHead> 组件(将呈现每条消息的当前用户缩略图),而不必通过所有中间组件从根组件一直传递它?

How would you make the current user information available to the <MessageUserHead> component (that will render the current user thumbnail for each message) without having to pass it along all the way from the root component thru all the intermediate components?

以同样的方式,如何在不借助于暴露整个状态对象的情况下,如何为组件树中的每个表示/哑元组件提供当前语言,主题等信息?

In the same way, how would you make information like current language, theme, etc available to every presentational/dumb component in the component tree without resorting to exposing the whole state object?

推荐答案

对于所有哑组件的全局信息,您可以使用。

For information that is global to all of your "dumb" components, you could use react contexts.

一个人为的例子

// redux aware component
var ChatApp = React.createClass({
  childContextTypes: {
    language: React.PropTypes.string
  },
  getChildContext: function() {
    // or pull from your state tree
    return {language: "en"};
  },
  ...
}

// dumb components
var ExDumb = React.createClass({
  contextTypes: {
    language: React.PropTypes.string
  },

  render: function() {
    var lang = this.context.language;
    return ( <div /> );
   }
 });

为了回应这些评论,redux使用了这个。

In response to the comments, redux uses this context approach in their react-redux library.

更抽象地用于反应之外,你可以使用某种采摘或在状态树上,并且只返回哑组件所需的全局状态的子集。

And more abstractly for use outside of react, you could use some sort of pluck or selector function on the state tree, and return only a subset of the global state needed by dumb components.

这篇关于如何在Redux中将全局状态数据处理为深层嵌套组件?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

09-24 15:59