React-redux no result apears

Viewed 24

I'm using React redux to build a div of a number that you can raise or to subtract. enter image description here

the problem is that everything seems to look good but there is no result on the browser

reducer-> index.js:

    import { combineReducers } from 'redux'
    
    const sumReducer = (sum = 0, action) => {
        if (action.type === 'ADD' || action.type === 'SUB') {
            let x = action.payload;
            return x;
        }
    
        return sum;
    }
    
    export default combineReducers({
        sum: sumReducer
    });

**action-> index.js**

export const add = (sum) => {
    return {
        type: 'ADD',
        payload: sum + 1
    }
}

export const sub = (sum) => {
    return {
        type: 'SUB',
        payload: sum  - 1
    }
}

my component is: upDownSum.js

    import React from 'react'
    import { connect } from 'react-redux'
    import { add, sub } from '../action'
    
    class UpDownSum extends React.Component {
        render() {
            console.log(this.props);
            console.log("ghj");
            return (
                <div key="1">
                    <button onClick={() => sub(this.props.sum)}>-</button>
                    <div>{this.props.sum}</div>
                    <button onClick={() => add(this.props.sum)}>+</button>
                </div>
    
            )
        }
    }
    const MapStateToProps = (state) => {
        return {
            sum: state.sum
        }
    }
    
    export default connect(MapStateToProps, {add: add ,sub: sub})(UpDownSum);

app.js import './App.css'; import UpDownSum from './upDownSum'

function App() {
  return (
    <UpDownSum/>
  );
}

export default App;

Thank you!

1 Answers

You are mapping dispatch to props, meaning to dispatch actions you will need to make sure to use props and not just the imported actions:

return (
  <div>
    <button onClick={() => this.props.sub(this.props.sum)}>-</button>
    <div>{this.props.sum}</div>
    <button onClick={() => this.props.add(this.props.sum)}>+</button>
  </div>
)
Related