我正在尝试根据所单击的按钮来识别Student
或Counselor
。
我要实现的目标是,如果用户单击Counselor
按钮,isCounselor
将变为true
,如果单击另一个按钮,则{{1} }将变成isStudent
。
我已经尝试过true
和onClick
,但是状态保持不变。
因此,我相信我做错了事,但不确定在哪里。我刚刚开始使用onSubmit
,却无法理解!
react-redux
中包含了reducer,并且我在下面的代码中创建了类型:
减速器
combineReducers
动作
import { IS_COUNSELOR, IS_STUDENT } from "../actions/types";
const initialState = {
isCounselor: false,
isStudent: false,
};
export default function (state = initialState, action) {
switch (action.type) {
case IS_COUNSELOR:
return {
...state,
isCounselor: true,
isStudent: false,
};
case IS_STUDENT:
return {
...state,
isCounselor: false,
isStudent: true,
};
default:
return state;
}
}
组件
import { IS_COUNSELOR, IS_STUDENT } from "./types";
// IS COUNSELOR
export const toCounselor = () => {
return {
type: IS_COUNSELOR,
payload: { isCounselor, isStudent },
};
};
// IS STUDENT
export const toStudent = () => {
return {
type: IS_STUDENT,
payload: { isCounselor, isStudent },
};
};
能否请您指教?谢谢!
答案 0 :(得分:2)
您的Welcome组件似乎未连接到redux状态,因此它没有从存储接收数据,并且未在redux循环中分派操作。
以下代码尚未准备就绪,但应该为您提供工作路径
// Connect the Redux Store (state) to the component props
const mapStateToProps = (state) => ({
isCounselor: state.isCounselor,
isStudent: state.isStudent,
});
// Updated thanks to the comment of Drew Reese below
const mapDispatchToProps = { toCounselor, toStudent };
// Previous version
// const mapDispatchToProps = dispatch => bindActionCreators({ toCounselor, toStudent }, dispatch);
export default connect(
mapStateToProps,
mapDispatchToProps
)(Welcome)
您应该看看此section of the documentation和here about the bindActionCreators
答案 1 :(得分:0)
在您的操作文件中,执行此操作...
import { IS_COUNSELOR, IS_STUDENT } from "./types";
// IS COUNSELOR
export const toCounselor = () => ({ type: IS_COUNSELOR });
// IS STUDENT
export const toStudent = () => ({ type: IS_STUDENT });
在渲染器内部,将函数传递到onClick
组件的Link
道具
然后在组件的末尾,执行此操作...
const mapStateToProps = (state) => ({
isCounselor: state.isCounselor,
isStudent: state. isStudent,
});
const mapDispatchToProps = { toCounselor, toStudent };
export default connect(
mapStateToProps,
mapDispatchToProps
)(Welcome)