File tree Expand file tree Collapse file tree 2 files changed +41
-9
lines changed Expand file tree Collapse file tree 2 files changed +41
-9
lines changed Original file line number Diff line number Diff line change @@ -10,22 +10,27 @@ class Subscriber extends React.Component {
1010 static propTypes = {
1111 channel : PropTypes . string . isRequired ,
1212 children : PropTypes . func ,
13+ quiet : PropTypes . bool
14+ }
15+
16+ static defaultProps = {
17+ quiet : false
1318 }
1419
1520 static contextTypes = {
1621 broadcasts : PropTypes . object
1722 }
1823
1924 state = {
20- value : null
25+ value : undefined
2126 }
2227
2328 getBroadcast ( ) {
2429 const broadcasts = this . context . broadcasts || { }
2530 const broadcast = broadcasts [ this . props . channel ]
2631
2732 invariant (
28- broadcast ,
33+ this . props . quiet || broadcast ,
2934 '<Subscriber channel="%s"> must be rendered in the context of a <Broadcast channel="%s">' ,
3035 this . props . channel ,
3136 this . props . channel
@@ -35,19 +40,27 @@ class Subscriber extends React.Component {
3540 }
3641
3742 componentWillMount ( ) {
38- this . setState ( {
39- value : this . getBroadcast ( ) . getState ( )
40- } )
43+ const broadcast = this . getBroadcast ( )
44+
45+ if ( broadcast ) {
46+ this . setState ( {
47+ value : broadcast . getState ( )
48+ } )
49+ }
4150 }
4251
4352 componentDidMount ( ) {
44- this . unsubscribe = this . getBroadcast ( ) . subscribe ( value => {
45- this . setState ( { value } )
46- } )
53+ const broadcast = this . getBroadcast ( )
54+
55+ if ( broadcast ) {
56+ this . unsubscribe = broadcast . subscribe ( value => {
57+ this . setState ( { value } )
58+ } )
59+ }
4760 }
4861
4962 componentWillUnmount ( ) {
50- this . unsubscribe ( )
63+ if ( this . unsubscribe ) this . unsubscribe ( )
5164 }
5265
5366 render ( ) {
Original file line number Diff line number Diff line change 1+ import React from "react"
2+ import ReactDOMServer from "react-dom/server"
3+ import Subscriber from "../Subscriber"
4+
5+ describe ( "A <Subscriber>" , ( ) => {
6+ it ( "throws an invariant when it is not rendered in the context of a <Broadcast>" , ( ) => {
7+ expect ( ( ) => {
8+ ReactDOMServer . renderToStaticMarkup ( < Subscriber channel = "cupcakes" /> )
9+ } ) . toThrow ( )
10+ } )
11+
12+ describe ( "with quiet=true" , ( ) => {
13+ it ( "does not throw when it is not rendered in the context of a <Broadcast>" , ( ) => {
14+ expect ( ( ) => {
15+ ReactDOMServer . renderToStaticMarkup ( < Subscriber quiet channel = "cupcakes" /> )
16+ } ) . not . toThrow ( )
17+ } )
18+ } )
19+ } )
You can’t perform that action at this time.
0 commit comments