/
shouldBroadcast.js
78 lines (60 loc) · 1.52 KB
/
shouldBroadcast.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
import React from 'react';
import createContext from '../src';
const { broadcasts, observes } = createContext('app');
@broadcasts(['language', 'name'])
class Broadcaster extends React.Component {
constructor(props, context) {
super(props, context);
this.state = {
language: 'en',
name: 'World',
};
// Replaces initial `getChildContext`
this.broadcast(props, this.state);
setTimeout(() => this.setState({ language: 'fr' }), 1000);
setTimeout(() => this.setState({ name: 'React' }), 2000);
}
componentWillUpdate(nextProps, nextState) {
// Replaces `shouldUpdateChildContext`
if (this.shouldBroadcast(nextProps, nextState)) {
// Replaces subsequent `getChildContext`
this.broadcast(nextProps, nextState);
}
}
shouldBroadcast(nextProps, nextState) {
return nextState['name'] !== this.state['name'];
}
broadcast(props, state) {
props.broadcast(state);
}
render() {
console.log('Broadcaster rendered');
return (
<Blocker>
<Subscriber />
</Blocker>
);
}
}
@observes(['language', 'name'])
class Subscriber {
render() {
console.log('Subscriber rendered');
return (
<ul>
<li>Language: {this.props.language}</li>
<li>Name: {this.props.name}</li>
</ul>
);
}
}
class Blocker {
shouldComponentUpdate() {
return false;
}
render() {
console.log('Blocker rendered');
return React.Children.only(this.props.children);
}
}
React.render(<Broadcaster />, document.body);