[英]Redux Updating Objects State
计数器减速器; 每当按下按钮时,我都试图增加计数器状态(对象)。 但不确定如何将对象 state 更新为 1(递增)和 -1(递减)。 每次我单击 + 按钮并使用 state+ 1 更新对象 state 时,我都会在上面得到这个 ^
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;
应用程序/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;
行动
export const increment = (x) => {
return{
type : 'INCREMENT',
}
}
export const decrement = (x) => {
return{
type : 'DECREMENT',
}
}
索引.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')
);
在
case 'INCREMENT':
return {...state,counter : state +1}
case 'DECREMENT':
return {...state,counter : state -1}
尝试
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;
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.