简体   繁体   中英

Redux Updating Objects State

counterReducer; I am trying to increase the counters state(object) whenever the button is pressed. But not exactly sure how to update the objects state by 1 (increment) and -1(decrement). 在此处输入图像描述 Every time I click the + button and update objects state with state+ 1 I get this above ^

const initialState = {
    counter: 0

}

const counter = (state=initialState,action) => {
    switch(action.type){
        case 'INCREMENT':
            return {...state,counter : state +1}
        case 'DECREMENT':
            return {...state,counter : state -1}
        default:
            return state;  state
    }
}

export default counter; 

app./js

import React from 'react';
import {useSelector,useDispatch} from 'react-redux';
import  { decrement, increment} from './Actions/counterAction'

function App() {
  const counter = useSelector(state => state.counter) // pull out counters state which is zerp
  const dispatch = useDispatch();
  return (
    <div className="App">
      <h1> counter {counter}</h1>
      <button onClick ={() => dispatch(increment())}> + </button> 
      <button onClick ={() => dispatch(decrement())}> - </button> 
    </div>
  );
}

export default App;

Action

export const increment = (x) => {
    return{
        type : 'INCREMENT',

    }
}
export const decrement = (x) => {
    return{
        type : 'DECREMENT',

    }
}

Index.js

import React from 'react';
import ReactDOM from 'react-dom';
import './index.css';
import App from './App';
import reportWebVitals from './reportWebVitals';
import { createStore } from 'redux';
import counter from './Reducers/counterReducer';
import { Provider } from 'react-redux'//make global  


const myStore = createStore(counter)

ReactDOM.render(
  <Provider store ={myStore}>  
    <App />
</Provider>,
  document.getElementById('root')
);

In

case 'INCREMENT':
            return {...state,counter : state +1}
        case 'DECREMENT':
            return {...state,counter : state -1}

Try

case 'INCREMENT':
            return {...state, counter : counter + 1 }
        case 'DECREMENT':
            return {...state, counter : counter - 1 } 
const initialState = {
    counter: 0

}

const counter = (state=initialState,action) => {
    switch(action.type){
        case 'INCREMENT':
            return {...state,counter : state.counter +1}
        case 'DECREMENT':
            return {...state,counter : state.counter -1}
        default:
            return state;  state
    }
}

export default counter; 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM