React-Redux 渲染刷新崩溃



我有一个带有Redux的Mern应用程序。我有一个问题。配置文件组件在两种情况下崩溃。1(在构建版本中刷新页面后.2(从直接地址栏进行Proiles路由时。(用于减小大小的较短代码(

1(配置文件.js组件通过"getProfiles"操作方法呈现所有配置文件来自redux状态。

return (
<Fragment>
{loading ? (
<Spinner />
) : (
<Fragment>
<h1 className="large text-primary">Profiles</h1>
<p className="lead">Üyeleri ve grupları keşfedin</p>
<div className="form">
<div className="form-group">
<input
type="text"
placeholder="İsim"
name="company"
value={company}
onChange={(e) => onChange(e)}
/>{" "}
</div>{" "}
</div>
<div
className=" lead d-flex align-items-center"
onClick={() => setOpen(!open)}
>
</div>
<div className="profiles">
{profiles.length > 0 ? (
profiles.map(
(profile) =>
profile.user._id !== user._id && (
<ProfileItem
key={profile._id}
followUser={followUser}
unFollowUser={unFollowUser}
profile={profile}
user={user}
/>
)
)
) : (
<h4>No Profile</h4>
)}
</div>
</Fragment>
)}
</Fragment>
);
};

配置文件的 Redux 操作.js

export const getProfiles = (
page,
start,
graduation,
mentorship,
scholarship,
representative,
company
) => async (dispatch) => {
const limit = 10;
const payload = {
params: {
page,
start,
limit,
graduation,
mentorship,
scholarship,
representative,
company,
},
};
console.log(page);
console.log(payload);
try {
const res = await axios.get("/api/profile", payload);
console.log(res.data.profiles);
dispatch({
type: GET_PROFILES,
payload: { profiles: res.data.profiles, totalPages: res.data.totalPages },
});
console.log(res.data);
} catch (err) {
dispatch({
type: PROFILE_ERROR,
payload: { msg: err.response.statusText, status: err.response.status },
});
}
};

型材减速器.js

case GET_PROFILES:
return {
...state,
profiles: payload.profiles,
totalPage: payload.totalPages,
loading: false,
};

当我使用反应路由器组件从导航中单击时,它很好。但是当我刷新或直接从地址栏转到页面时,它会崩溃。控制台中的这些错误

刷新/地址栏渲染崩溃

页面仅在 buid 模式下崩溃。在开发模式下很好。我试图更改条件(加载等(但一切都没有改变。

任何帮助将不胜感激。 谢谢!

问题似乎不在于配置文件,而在于用户_id。最初,在配置文件组件的首次渲染中,用户为 null,因此您得到的错误_id为 null。

尝试检查用户是否存在,然后渲染配置文件。就像在个人资料中一样.js

if(!user){
return null
}
return (
<Fragment> 
// yor rest code
</Fragment>

此外,使用控制台.log检查页面加载后配置文件的用户属性是否显示为空。

我不确定,但您可以验证以避免第一个错误,我的意思是"_id"错误:

<div className="profiles">
{ 
profiles.length > 0 && user ? (
profiles.map((profile) => {
if (profile.user && profile.user._id !== user._id) {
return (
<ProfileItem
key={profile._id}
followUser={followUser}
unFollowUser={unFollowUser}
profile={profile}
user={user}
/>
);
}
})
) : (
<h4>No Profile</h4>
)
}
</div>;

状态文本错误是因为配置文件中的尝试捕获中存在错误.js当您想要调度PROFILE_ERROR操作时,您正在尝试从err.response.statusText访问statusText,但err.response未定义。

最新更新