2019年05月14日

ReactでpropsとRecomposeとReduxでpropsを引き渡すサンプル

Reactでpropsとして受け取る値には親要素から受け取ったprops以外に、RecomposeでEnhanceされたporpsやstate、Reduxでconnectされたstoreの値などがあるので出し分けのサンプル

import React, { useState } from "react";
import ReactDOM from "react-dom";
import { compose, withStateHandlers } from "recompose";
import { createStore } from "redux";
import { Provider, connect } from "react-redux";

const Foo = ({ no, changeNo, no2, changeNo2, no3, changeNo3 }) => {
const handleClick = () => {
changeNo(no + 1);
};
const handleClick2 = () => {
changeNo2(no2 + 1);
};
const handleClick3 = () => {
changeNo3(no3 + 1);
};
return (
<div>
<p>props:{no}</p>
<input value="+" type="button" onClick={handleClick} />
<p>recomoseState:{no2}</p>
<input value="+" type="button" onClick={handleClick2} />
<p>connectedState:{no3}</p>
<input value="+" type="button" onClick={handleClick3} />
</div>
);
};

const ConnectedFoo = connect(
state => ({
no3: state.no3
}),
dispatch => ({
changeNo3: no => {
dispatch(changeNo3(no));
}
})
)(Foo);

const EnhancedFoo = compose(
withStateHandlers(
() => ({
no2: 0
}),
{
changeNo2: props => () => ({
no2: props.no2 + 1
})
}
)
)(ConnectedFoo);

const App = () => {
const [no, changeNo] = useState(0);
return (
<div>
<EnhancedFoo no={no} changeNo={changeNo} />
</div>
);
};

function changeNo3(no3) {
return {
type: "CHANGE_NO3",
no3
};
}

const initialState = {
no3: 0
};

const store = createStore((state = initialState, action) => {
switch (action.type) {
case "CHANGE_NO3":
return {
no3: action.no3
};
default:
return state;
}
});

const rootElement = document.getElementById("root");
ReactDOM.render(
<Provider store={store}>
<App />
</Provider>,
rootElement
);


posted by ねこまんま at 03:51 | React | 更新情報をチェックする