How to handle global state data into deeply nested components in Redux?

后端 未结 2 1593
青春惊慌失措
青春惊慌失措 2021-01-31 22:30

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


  ...
  ...<         


        
2条回答
  •  一向
    一向 (楼主)
    2021-01-31 23:10

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

    A contrived example

    // 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 ( 
    ); } });

    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.

提交回复
热议问题