Redux基礎⑥

つぎにHooksを使って書き換えていきましょう。

 

まず、useSelectorを使って、mapStateToPropsの存在を消し去ります。

 

[プロジェクト名]/src/components/App.js


import {INCREASE_COUNT} from "../actions";
import {connect} from 'react-redux';
import {useSelector} from 'react-redux';

function App({increase}) {
  const count = useSelector((state) => state.count);
  return (
    <div>
       <p>MyReact</p>
       <p>{count}</p>
       <button type="button"
               onClick={increase}>UP</button>
    </div>
  );
}

const mapDispatchToProps = (dispatch) =>{
  return{
      increase: () => dispatch({type: INCREASE_COUNT}),
  }
}

export default connect(null, mapDispatchToProps)(App);


[プロジェクト名]/src/actions/index.js

export const INCREASE_COUNT = "INCREASE_COUNT";

export function increaseCount(count){
    return{
        type: INCREASE_COUNT,
        count:count,
    }
}

[プロジェクト名]/src/reducers/Counter.js

import {INCREASE_COUNT} from '../actions';

const initialState = {
    count: 0
}

function Counters(state = initialState, action){
    switch(action.type){
        case INCREASE_COUNT:
            return{
                ...state,
                count: state.count + 1,
            }
        default:
            return state;
    }

}

export default Counters;

[プロジェクト名]/src/index.js →そのまま