【问题标题】:Dispatch not changing redux state调度不改变 redux 状态
【发布时间】:2019-02-20 08:25:21
【问题描述】:

我对 redux 还很陌生,遇到了问题。

我正在尝试在我的登录页面中实现 Flash 消息,但 redux 的调度并未改变 UI 状态。

我希望在用户成功注册后,在登录页面上显示一条消息。

//login.js

class Login extends Component{
    renderMessage() {
        if (this.props.flashMessageType== "registrationComplete"){
            return (
                <Message
                    style={{textAlign: "left"}}
                    success
                    icon="check circle"
                    header="Account Registration was Successful"
                    list={["You must verify your email before logging in"]}
                />
            );
        } else {
            return (null);
        }
    }

    render() {
        return ({
            this.renderMessage()
        });
    }
}


function mapStateToProps(state) {
    return {
        flashMessageType:state.flashMessage.flashType,
    };
}


export default connect(mapStateToProps, actions)(Login);

这里是减速器

const initialState = {
    flashType: "",
};

export default function(state = {initialState}, action){
    switch(action.type){
        case USER_REGISTER:
            return [
                ...state,
                {
                    flashType:"registrationComplete"
                }
            ];
        default:
            return initialState;
    }
}

这里是动作

export const submitForm = (values,history) => async dispatch => {
    const res = await axios.post('/api/signup', values);
    history.push('/');
    dispatch({type: FETCH_USER, payload: res.data});
    dispatch({type: USER_REGISTER});
};

感谢您的帮助。

谢谢,

文森特

【问题讨论】:

  • 控制台出现什么错误?
  • @AmrAly 我在控制台中没有收到任何错误。当我查看由 axios 发出的 post 请求时。我找到了 302。我不知道这是什么意思
  • 所以你被重定向但没有消息出现?
  • @AmrAly 是的。我被重定向到登录页面,reducer 中的状态没有更新。
  • 您的初始状态是一个对象,但您在USER_REGISTER 操作中返回一个数组尝试将其更改为对象return { ...state, flashType:"registrationComplete" } 并查看是否有效

标签: reactjs redux redux-thunk


【解决方案1】:

正如 Amr Aly 提到的(现在很糟糕),当你这样做时,你实际上是在改变状态:

return[ ...state, { flashType:"registrationComplete" }]

你真正想要的是:

return { ...state, flashMessage: "registrationComplete" }

此外,您的某些代码有点多余和/或缺少一些重要指令(例如 try/catch 块)。

你的代码应该是什么样子:

FlashMessage.js

import React, { PureComponent } from 'react';
import Message from '../some/other/directory';
import actions from '../some/oter/directory':

class Login extends PureComponent {
  render = () => (
    this.props.flashMessage == "registrationComplete"
     ? <Message
         style={{textAlign: "left"}}
         success
         icon="check circle"
         header="Account Registration was Successful"
         list={["You must verify your email before logging in"]}
       />
     : null
  )
}    

export default connect(state => ({ flashMessage: state.auth.flashMessage }), actions)(Login)

reducers.js

import { routerReducer as routing } from 'react-router-redux';
import { combineReducers } from 'redux';
import { FETCH_USER, USER_REGISTER } from '../actions/types';

const authReducer = (state={}, ({ type, payload }) => {
  switch(type){
    case FETCH_USER: return { ...state, loggedinUser: payload };
    case USER_REGISTER: return { ...state, flashMessage: "registrationComplete" }
    default: return state;
  }
}

export default = combineReducers({
  auth: authReducer,
  routing
});

actions.js

import { FETCH_USER, USER_REGISTER } from './types';

export const submitForm = (values,history) => async dispatch => {
  try {
    const {data} = await axios.post('/api/signup',values);
    dispatch({ type:FETCH_USER, payload: data });
    dispatch({ type:USER_REGISTER });
    history.push('/');
  catch (err) {
    console.error("Error: ", err.toString());
  }
};

【讨论】:

  • 感谢您的提示!我真的很感谢马特卡罗塔!
  • 你打赌。需要注意的重要一点是,在使用 async/await 时,您需要执行 try/catch 块。否则,如果请求失败,您的应用会崩溃和/或显示无效数据。
【解决方案2】:

你的减速器应该是:

const initialState = {
    flashType: "",
};

export default function(state = initialState, action){
    switch(action.type){
        case USER_REGISTER:
            return {
                ...state,
                flashType: "registrationComplete",
            };
        default:
            return state;
    }
}

【讨论】:

  • @VincentLaw 别提了 ;)
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2019-02-24
  • 2019-01-30
  • 2016-06-27
  • 2020-12-07
  • 1970-01-01
  • 2019-03-19
相关资源
最近更新 更多