您好,我正在尝试为我的一个React组件之一编写单元测试,并且不断收到相同的错误TypeError:无法读取未定义的属性“名称”。我将状态传递为defaultValue
,并使用''
对其进行了初始化。我对shallow
的所有测试都失败了。
这是我的文件:
const EditProfileContainer = () => {
const dispatch = useDispatch();
React.useEffect(() => {
dispatch(getProfileDataAction());
}, [dispatch]);
const profileReducer = useSelector(
(state) => state.profileReducer.profileData,
);
const [name, setNewName] = React.useState('');
const [phone, setNewPhone] = React.useState('');
const handleNewName = (event) => {
setNewName({ [event.target.name]: event.target.value });
};
const handlenewPhone = (event) => {
setNewPhone({ [event.target.name]: event.target.value });
};
const handleProfileSubmit = (event) => {
event.preventDefault();
dispatch(editProfileAction(name, phone));
};
return (
<EditProfile
onNameChange={handleNewName}
onPhoneChange={handlenewPhone}
onProfileSubmit={handleProfileSubmit}
profileState={profileReducer}
/>
);
};
export default EditProfileContainer;
这就是我使用profileState
道具的方式。
const EditProfile = ({
onNameChange, onPhoneChange, onProfileSubmit, profileState,
}) => (
<>
<p className='account-title'>ACCOUNT DETAILS</p>
<Card className='registery-card mb-5'>
<Card.Body>
<Form className='password-form' onSubmit={onProfileSubmit}>
<Form.Group controlId='formBasicProfile'>
<Form.Label className='password-label'>
Name
</Form.Label>
<Form.Control
size='sm'
type='text'
placeholder='Enter Name'
name='name'
defaultValue={'' || profileState.name}
pattern={`${pattern}`}
title='First name or Last name must contain at least three characters'
className='password-text-field'
onChange={onNameChange}
/>
</Form.Group>
<Form.Group controlId='formBasicProfilePhone'>
<Form.Label className='password-label'>
{' '}
Phone
</Form.Label>
<Form.Control
size='sm'
type='number'
placeholder='New Phone number'
defaultValue={'' || profileState.phone}
name='phone'
className='password-text-field'
onChange={onPhoneChange}
/>
</Form.Group>
<Button
variant='primary'
type='submit'
className='register-btn d-inline float-right mt-3'
onSubmit={onProfileSubmit}
>
Save
</Button>
</Form>
</Card.Body>
</Card>
</>
);
export default EditProfile;
这是错误
TypeError: Cannot read property 'name' of undefined
23 | placeholder='Enter Name'
24 | name='name'
> 25 | defaultValue={'' || profileState.name}
| ^
26 | pattern={`${pattern}`}
27 | title='First name or Last name must contain at least three characters'
28 | className='password-text-field'
答案 0 :(得分:0)
profileState
对象为undefined
,因此尝试访问其name
道具会引发错误。
您可以显式检查其是否存在,为profileState
设置默认值,或使用类似可选的链接:profileState?.name