从非组件JS文件分派动作后,重新渲染组件

时间:2019-06-07 05:46:27

标签: reactjs redux react-redux

我正在使用store.dispatch()从非组件JS(utils / index.js)文件调度操作,但是在reducer状态更改后,未使用mapStateToProps连接该reducer状态的组件。被重新渲染,

我在做什么错了?

任何帮助将不胜感激


预先感谢


  

我尝试进行搜索,找到所有从组件文件中分派动作的问题和文章。


所有相关文件

/store/index.js


import { createStore } from "redux";
import rootReducer from "reducers";

store = createStore(rootReducer);

/utils/index.js

import store from './store';
import { toggleShowAlert } from "reducers/alert";

export const customAlert = msg => {
    store.dispatch(toggleShowAlert(msg));
}

/views/Nav/index.js

import React, { Component } from 'react';
import { connect } from 'react-redux';

class Nav extends Component {
    render() {
        ....
        // component code
        ....
    }
}

const mapStateToProps = state => {
    return {
        showAlert: state.alert.showAlert
    }
}

export default connect(mapStateToProps)(Nav);

/reducer/alert.js

const TOGGLE_SHOW_ALERT = "TOGGLE_SHOW_ALERT";

export const toggleShowAlert = msg => {
    return dispatch => {
        dispatch({
            type: TOGGLE_SHOW_ALERT,
            msg
        });
    };
};

const initialState = {
    showAlert: false,
    alertMsg: ""
};

const reducer = (state = initialState, action) => {
    switch (action.type) {
        case TOGGLE_SHOW_ALERT:
            return {
                ...state,
                showAlert: !state.showAlert,
                alertMsg: state.showAlert ? "" : action.msg
            };
        default:
            return { ...state };
    }
}

export default reducer;

被称为customAlert的另一个简化器 /reducers/user.js

import { customAlert } from 'utils';

...other codes...

export const updateAgeGender = (userId, age, gender) => {
    return dispatch => {
        dispatch(updateButtonLoading());
        callAPI("post", `${COMM_BE_URL}/users/update-age-gender`, {
            userId,
            age,
            gender
        })
        .then(res => {
            if (res.status === "SUCCESS") {
                dispatch(updateAgeGenderAction(age, gender));
                customAlert("Your info has been updated, now u can join");
            }
        })
        .catch(err => {
            console.log(err);
            dispatch(updateError(SERVER_ERROR_MSG));
        });
    };
};

更改showAlert后,导航组件应重新渲染,但没有发生

0 个答案:

没有答案