在Redux中将多个动作传递给mapDispatchToProps

时间:2018-12-29 18:52:44

标签: javascript reactjs ecmascript-6 redux react-redux

我尝试在此组件中使用3个动作。一个使我退出了Firebase Google Auth(工作正常),另外两个只是将状态更改为某个字符串,稍后将用它来确定要渲染的组件。

已注释掉的mapDispatchToProps可以正常工作,这是我习惯编写它的方式,使用logout方法的一种语法我无法弄清楚。如何重构以下内容,以便setRoutines和setExercises起作用?

组件:

import React from 'react';

import { connect } from "react-redux";
import { firebaseLogout } from '../Auth/Auth.actions';
import { setRoutines, setExercises } from './Profile.actions';

const Profile = ({logout, setRoutines, setExercises}) => (
    <React.Fragment>
        <button onClick={setRoutines}>My Routines</button>
        <button onClick={setExercises}>My Exercises</button>
        <button onClick={logout}>Logout</button>
    </React.Fragment>
);

const mapDispatchToProps = (dispatch) => ({
    logout: () => dispatch(firebaseLogout()),
    setRoutines,
    setExercises,
});

// const mapDispatchToProps = {
//     setRoutines,
//     setExercises
// };

export default connect(
  undefined,
  mapDispatchToProps
)(Profile);

我的操作文件:

export const setRoutines = () => ({
    type: "SET_ROUTINES",
    payload: "routines"
});
export const setExercises = () => ({
    type: "SET_EXERCISES",
    payload: "exercises"
});

export const logout = () => ({
    type: 'LOGOUT'
});

export const firebaseLogout = () => {
    return () => {
        return firebase.auth().signOut();
    }
};

我的减速器文件:

export default (state = {view:'routines'}, action) => {
    switch (action.type) {
        case 'SET_ROUTINES':
            return {
                ...state,
                view: action.payload
            };

        case 'SET_EXERCISES':
            return {
                ...state,
                view: action.payload
            };

        case 'LOGOUT':
            return {};

        default:
            return state;
    }
};

1 个答案:

答案 0 :(得分:2)

通过将mapDispatchToProps修改为以下提及的格式,应该有助于创建自动分派的绑定动作创建者。

const mapDispatchToProps = (dispatch) => ({
    logout: () => dispatch(firebaseLogout()),
    boundRoutines: () => dispatch(setRoutines()), 
    boundExercises: () => dispatch(setExercises()),
});

创建绑定动作创建者后,我们可以按以下方式调用创建者。

const Profile = ({logout, boundRoutines, boundExercises}) => (
    <React.Fragment>
        <button onClick={boundRoutines}>My Routines</button>
        <button onClick={boundExercises}>My Exercises</button>
        <button onClick={logout}>Logout</button>
    </React.Fragment>
);