reactjs - 调度不改变 redux 状态

标签 reactjs redux redux-thunk

我对 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);

这是 reducer
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});
};

我感谢您的帮助。

谢谢,

文森特

最佳答案

正如 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());
  }
};

关于reactjs - 调度不改变 redux 状态,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52350336/

相关文章:

javascript - 我为状态创建了一个通用的 reducer ,什么时候应该使用它什么时候不应该使用它

reactjs - 保证发货顺序

javascript - 当其中一个获取延迟响应时,如何在 Redux 中进行多次获取操作?

javascript - 如何转换返回 promise 使用异步/等待的 redux-thunk 操作?

javascript - 用多个值 react native setState

javascript - 为什么 React-router Link 不起作用(ReactJS + Redux)?

javascript - 用 enzyme 和 connect() 进行开 Jest 测试,给出 `import connectAdvanced from ' ../components/connectAdvanced';`

django - 由于 SyntaxError,Webpack 无法 bundle

javascript - 对象作为 React 子对象无效(在 React 15.4.1 的 Internet Explorer 11 中)

javascript - 当我看不到 api 结果时,我需要显示未找到数据