在app.js中,当按下按钮时,isLogged状态从false更改为True,但是组件仍在呈现No !,而不是Yes!。如条件运算符中所示。我了解它不会违反可变性规则,因为!state不会改变状态本身。 React-redux版本:7.2.0,redux版本:4.0.5
export const increment = (nr) => {
return{
type: 'INCREMENT',
payload: nr
};
};
export const decrement = () => {
return{
type: 'DECREMENT'
};
};
export const signin = () => {
return{
type: 'SIGN_IN'
};
};
const counterReducer = (state = 0, action) => {
switch(action.type){
case 'INCREMENT':
return state + action.payload;
case 'DECREMENT':
return state - 1
default: //MUST HAVE A DEFAULT STATE **
return state
}
}
export default counterReducer;
const loggedReducer = (state = false, action) => {
switch(action.type){
case "SIGN_IN":
return !state;
default:
return state;
}
};
export default loggedReducer;
import counterReducer from './counter';
import loggedReducer from './isLogged';
import {combineReducers} from 'redux';
const mainReducer = combineReducers({
counter: counterReducer,
islogged: loggedReducer
})
export default mainReducer;
import {createStore} from 'redux';
import mainReducer from './reducers';
import { Provider } from 'react-redux';
const store = createStore(mainReducer,
window.REDUX_DEVTOOLS_EXTENSION && window.REDUX_DEVTOOLS_EXTENSION());
ReactDOM.render(
<React.StrictMode>
<Provider store={store}>
<App />
</Provider>
</React.StrictMode>,
document.getElementById('root')
);
import React from 'react';
import {useSelector, useDispatch} from 'react-redux';
import {increment, decrement, signin} from './actions';
function App(){
const counter = useSelector(state => state.counter);
const isLogged = useSelector(state=> state.isLogged);
const dispatch = useDispatch();
return (
<div className="App">
<h1>Counter {counter}</h1>
<button onClick={()=> dispatch(increment(5))}>+</button>
<button onClick={()=> dispatch(decrement())}>-</button>
<button onClick={() => dispatch(signin())}>Log in</button>
<h1>Are you logged in { isLogged ? "Yes!" : "No!"}</h1>
</div>
);
}
export default App;