Skip to content

Instantly share code, notes, and snippets.

@MaxMEllon
Last active December 29, 2017 07:55
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save MaxMEllon/31652df15d90f2ac7bb4fea48a221295 to your computer and use it in GitHub Desktop.
Save MaxMEllon/31652df15d90f2ac7bb4fea48a221295 to your computer and use it in GitHub Desktop.
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} />
)
}
}
}
@MaxMEllon
Copy link
Author

redux の connect から オプションを削ぎ落とし simple にした例

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment