gpt4 book ai didi

javascript - 在 Redux 中将多个操作传递给 mapDispatchToProps

转载 作者:行者123 更新时间:2023-11-28 17:13:32 26 4
gpt4 key购买 nike

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

注释掉的mapDispatchToProps工作正常,这就是我习惯的编写方式,使用注销方法的语法是我无法弄清楚的。如何重构以下内容以便 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();
}
};

我的 reducer 文件:

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;
}
};

最佳答案

通过将 mapDispatchToProps 修改为下面提到的格式应该有助于创建自动分派(dispatch)的绑定(bind)操作创建者。

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

创建绑定(bind) Action 创建者后,我们可以按如下方式调用创建者。

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

关于javascript - 在 Redux 中将多个操作传递给 mapDispatchToProps,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53972457/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com