我正在处理ReactJS模态对话框,并通过useSelector钩子绑定redux切片中的值。目前,我有两个函数已经在使用useDispatch钩子进行调度,并用两个函数(onCancelHandler、submitHandler(设置道具。在这里,我需要保留另一个字段,即字符串值(userName(,并试图保留它,并通过道具在DeleteUserModalContext中使用字符串值approvedUser。最初,我能够从DeleteUserModalContent中的道具中获得值组件,但当执行submitHandler时,会发生以下错误。
无法读取未定义的属性"userName">
此行出错:const approvedUser:string=selectedUser.userName;
有人能告诉我这里出了什么问题吗?
提前感谢
代码段:
import React from 'react';
import { useDispatch, useSelector } from 'react-redux';
import { Modal } from '@material-ui/core';
import { AppState } from 'store/rootReducer';
import { hideModal } from 'store/common/modalSlice';
import { submitAction } from 'store/user-actions';
import { DeleteUserModalContent } from './DeleteUserModalContent';
export const DeleteUserModal: React.FC<{}> = () => {
const dispatch = useDispatch();
const selectedUser = useSelector((state: AppState) => {
const selectedUserId =
state.selectUserSlice.selectedUsers[0];
return state.userState[selectedUserId];
});
const onCancelHandler = () => {
dispatch(hideModal());
};
const submitHandler = () => {
dispatch(
submitAction(selectedUser.userName)
);
};
const approvedUser: string = selectedUser.userName;
console.log(selectedUser.userName);
const props = {
onResetHandler,
submitHandler,
approvedUser
};
return (
<Modal>
<>
<DeleteUserModalContent {...props} />
</>
</Modal>
);
};
当我们使用useSelector钩子的返回值,并通过设置到props在其他组件DeleteUserModalContext中使用相同的值时。在这里,我们最初可以使用approvedUser值,但当submitHandler函数被调度时,selectedUser.userName值变得未定义,因此我们可以在下面进行条件检查:
const approvedUser: string = selectedUser?.userName
以避免上述错误。