簡體   English   中英

reducer不會在react redux中更新狀態

[英]reducer does not update state in react redux

我正在使用react-redux嘗試更新狀態,但狀態未更新。 新值將在reducer中出現“if(action.type ==='SET_LOGGED_IN')”,但不會將isLoggedIn更新為true。 什么問題? 找到代碼

Login.js

function handleLoginClick(username, password, e) {
    e.preventDefault();

    post('/createUser', { username, password })
        .then(({ status }) => {
            if (status === 200) {
                console.log(this.props);
                this.props.setLoggedIn(true);
                this.props.history.push('/');
            }else{
                this.props.setLoggedIn(false);

            }
        })
        .catch(error => {
        .........
        })
}
..................
const mapStateToProps = state => {
    return {isLoggedIn : state.reducer.isLoggedIn};};
const mapDispatchToProps = dispatch => {
    return {setLoggedIn : (value) => dispatch({type: 'SET_LOGGED_IN', value: value}),}};

export default compose(
    withStyles(styles),
    withRouter,
    connect(mapStateToProps, mapDispatchToProps)
)(NewLogin);

reducer.js

import { combineReducers } from 'redux';
import { reducer as reduxFormReducer } from 'redux-form';

const initialStates = {
    isLoggedIn : false
};

const reducers = combineReducers({
    reducer : (state = initialStates, action) => {
        //console.log(action);
        if (action.type === 'SET_LOGGED_IN') {
            //console.log(action);
            return {
                ...state,
                isLoggedIn: action.value
            };
        }
        return state;
    },

        form: reduxFormReducer, // mounted under "form"
});

export default reducers;

- 修正錯誤 -

在我的代碼中,狀態正確更新。 當我訪問時,我使用了state.isLoggedIn,這是未定義的。 我從state.reducer.isLoggedIn替換它。 現在一切都很有魅力。

謝謝@UmairFarooq,@ VladimirBogomolov以及所有評論並嘗試修復它的人。

const mapStateToProps = state => {
    return {
      isLoggedIn : state.reducer.isLoggedIn
    };
};

認為mapStateToProps可能存在問題。 嘗試訪問isLoggedIn狀態,如:

const mapStateToProps = state => {
    return {isLoggedIn : state.isLoggedIn};};

使用componentwillupdate()來控制何時更新返回false以不更新

你應該以不同的方式調用派遣:

const mapDispatchToProps = (dispatch, val) => {
  return {
    setLoggedIn : (val) => dispatch({ type: 'SET_LOGGED_IN', value: val }),
  }
};

試試吧,它應該適合你。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM