|
1 | | -import React, { Component } from 'react' |
| 1 | +import React, { useMemo, useEffect } from 'react' |
2 | 2 | import PropTypes from 'prop-types' |
3 | 3 | import { ReactReduxContext } from './Context' |
4 | 4 | import Subscription from '../utils/Subscription' |
5 | 5 |
|
6 | | -class Provider extends Component { |
7 | | - constructor(props) { |
8 | | - super(props) |
9 | | - |
10 | | - const { store } = props |
11 | | - |
12 | | - this.notifySubscribers = this.notifySubscribers.bind(this) |
| 6 | +function Provider({ store, context, children }) { |
| 7 | + const contextValue = useMemo(() => { |
13 | 8 | const subscription = new Subscription(store) |
14 | | - subscription.onStateChange = this.notifySubscribers |
15 | | - |
16 | | - this.state = { |
| 9 | + subscription.onStateChange = subscription.notifyNestedSubs |
| 10 | + return { |
17 | 11 | store, |
18 | 12 | subscription |
19 | 13 | } |
| 14 | + }, [store]) |
20 | 15 |
|
21 | | - this.previousState = store.getState() |
22 | | - } |
| 16 | + const previousState = useMemo(() => store.getState(), [store]) |
23 | 17 |
|
24 | | - componentDidMount() { |
25 | | - this.state.subscription.trySubscribe() |
| 18 | + useEffect(() => { |
| 19 | + const { subscription } = contextValue |
| 20 | + subscription.trySubscribe() |
26 | 21 |
|
27 | | - if (this.previousState !== this.props.store.getState()) { |
28 | | - this.state.subscription.notifyNestedSubs() |
| 22 | + if (previousState !== store.getState()) { |
| 23 | + subscription.notifyNestedSubs() |
29 | 24 | } |
30 | | - } |
31 | | - |
32 | | - componentWillUnmount() { |
33 | | - if (this.unsubscribe) this.unsubscribe() |
34 | | - |
35 | | - this.state.subscription.tryUnsubscribe() |
36 | | - } |
37 | | - |
38 | | - componentDidUpdate(prevProps) { |
39 | | - if (this.props.store !== prevProps.store) { |
40 | | - this.state.subscription.tryUnsubscribe() |
41 | | - const subscription = new Subscription(this.props.store) |
42 | | - subscription.onStateChange = this.notifySubscribers |
43 | | - this.setState({ store: this.props.store, subscription }) |
| 25 | + return () => { |
| 26 | + subscription.tryUnsubscribe() |
| 27 | + subscription.onStateChange = null |
44 | 28 | } |
45 | | - } |
46 | | - |
47 | | - notifySubscribers() { |
48 | | - this.state.subscription.notifyNestedSubs() |
49 | | - } |
| 29 | + }, [contextValue, previousState]) |
50 | 30 |
|
51 | | - render() { |
52 | | - const Context = this.props.context || ReactReduxContext |
| 31 | + const Context = context || ReactReduxContext |
53 | 32 |
|
54 | | - return ( |
55 | | - <Context.Provider value={this.state}> |
56 | | - {this.props.children} |
57 | | - </Context.Provider> |
58 | | - ) |
59 | | - } |
| 33 | + return <Context.Provider value={contextValue}>{children}</Context.Provider> |
60 | 34 | } |
61 | 35 |
|
62 | 36 | Provider.propTypes = { |
|
0 commit comments