Last active
December 29, 2017 07:55
-
-
Save MaxMEllon/31652df15d90f2ac7bb4fea48a221295 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import { render } from 'react-dom' | |
import React from 'react' | |
import PropTypes from 'prop-types' | |
/** | |
* @example | |
* | |
* function App(props) { | |
* return ( | |
* ... | |
* ) | |
* } | |
* | |
* // connect されているので, props が store の state になる | |
* // 従来は,subscribeやaddEventListener で handle したイベントのコールバックで | |
* // setState しており,Component が状態を持っていた. | |
* // コンポーネントは,なるべく不変にしたいので,stateではなくpropsで扱いたい. | |
* // component 内 で state を書き換えると,誤ってstoreを直接書き換える可能性がある | |
* // Object.assign などで対策することもできる | |
* // ただ,これらのことを毎度考えるのは大変なので,HoCを使って state を propsに流し込む | |
* export default simpleConnect(<App />) | |
* | |
*/ | |
function simpleConnect(Component) { | |
return class extends React.Component { | |
static contextTypes = { | |
store: PropTypes.any, | |
} | |
constructor(props, context) { | |
super(props, context) | |
this.state = { } | |
} | |
componentDidMount() { | |
this.unsubscribe = this.context.store.subscribe(this.onChange.bind(this)) | |
} | |
componentWillUnmount() { | |
this.unsubscribe() | |
} | |
onChange(e) { | |
const state = this.context.store.getState() | |
this.setState({ state }) | |
} | |
render() { | |
const newProps = this.context.store.getState() | |
return ( | |
<Component {...this.props} {...newProps} /> | |
) | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
redux の connect から オプションを削ぎ落とし simple にした例