【发布时间】:2021-07-11 07:24:10
【问题描述】:
这是我试图获取用户数据并在代码的突出显示部分中出错的配置文件组件。为什么 userData 是未定义的??
import React, {useEffect} from 'react';
import {useDispatch, useSelector} from 'react-redux';
import { getUserProfile } from '../../actions/userActions';
import Styles from './Profile.module.scss';
const Profile = (props) => {
const userId = props.match.params.id;
const dispatch = useDispatch();
const userLogin = useSelector(state => state.userLogin);
const {userInfo} = userLogin;
**const userProfile = useSelector(state => state.userProfile);
const {loading, error, userData} = userProfile;
const {posts, data} = userData;**
useEffect(() => {
if(!userInfo){
props.history.push('/login');
}else{
dispatch(getUserProfile(userId));
}
}, [dispatch,userId])
return (
<section>
<div className={Styles.Container}>
<h1>{data.userName}</h1>
<h1>{data.followers.length} followers</h1>
<h1>{data.following.length} following</h1>
<h1>{posts.length} posts</h1>
</div>
</section>
)
}
export default Profile
这是 userProfile 的 Reducer 文件 -
export const userProfileReducer = (state={ userData: {}}, action) => {
switch(action.type){
case GET_USER_PROFILE_REQUEST:
return { loading: true, ...state, }
case GET_USER_PROFILE_SUCCESS:
return { ...state, loading: false, userData: action.payload}
case GET_USER_PROFILE_FAIL:
return { loading: false, error: action.payload}
default: return state;
}
}
我收到了这个错误
TypeError: Cannot destructure property 'posts' of 'userData' as it is undefined. Profile
【问题讨论】:
标签: javascript node.js reactjs react-redux react-router