Redux布尔状态更改,但未在组件中呈现

时间:2020-05-10 09:05:49

标签: javascript reactjs react-native redux react-redux

在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'
    };
};

counterReducer

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;

loggedReducer

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;

Index.JS

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')
);

App.JS

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;

0 个答案:

没有答案