C
C
cosonicsq2020-04-20 12:39:29
React
cosonicsq, 2020-04-20 12:39:29

How would this code look if instead of mapStateToProps and matchDispatch there were useSelector and useDispatch?

I have a class component. But I need to remake my component into a functional one and remake it accordingly so that instead of mapStateToProps and matchDispatch I have useSelector and useDispatch. But I have never used useSelector and useDispatch. And the react-redux documentation is not a very clear example.
The component implements a very simple functionality: When a button is pressed, the number to the right of the button increases by one.

Index.js:

//action
const plusLike = index => ({
    type: "PLUS_LIKE",
    payload:index
});

//reducer
const reducer = (state={like:0},action) =>{
    switch(action.type){
        case "PLUS_LIKE":
            return Object.assign({},state, {
               like: action.payload
            });
        default:
            return state
    }
};

//это должен быть функциональный компонент
class App extends React.Component{
    render(){
        return (
        <div>
           <button onClick={index => this.props.onPlusLike(this.props.onLike+1)}>Like</button>
          {this.props.onLike}   
        </div>                         
        );
    }
}

//mapStateToProps
const mapStateToProps = state => ({
    onLike: state.propReducer.like
});

//matchDispatchToProps
const matchDispatchToProps = dispatch =>({
    onPlusLike: index => dispatch(plusLike(index))
});

const allReducers = combineReducers({
    propReducer:reducer
});

const ConnectApp = connect(
     mapStateToProps,
     matchDispatchToProps
)(App);

const store = createStore(allReducers);

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

Answer the question

In order to leave comments, you need to log in

1 answer(s)
R
real2210, 2020-04-20
@cosonicsq

If very briefly

const like = useSelector(state => state.propReducer.like);

const dispatch = useDispatch();

///....
dispatch(onPlusLike(props.onLike+1))

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question