[英]React-Redux render refresh crash
我有一个带有 Redux 的 Mern 应用程序。 我有个问题。 Profiles 组件在两种情况下崩溃。 1)在构建版本中刷新页面后。2)直接从地址栏进入Proiles路由时。(用于减小大小的更短代码)
1)Profiles.js 组件通过“getProfiles”操作方法渲染来自 redux state 的所有配置文件。
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>
);
};
Profiles.js 的 Redux 操作
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 },
});
}
};
Profiles.js 的减速器
case GET_PROFILES:
return {
...state,
profiles: payload.profiles,
totalPage: payload.totalPages,
loading: false,
};
当我使用 React-routers 组件从导航中单击时,它很好。 但是当我直接从地址栏刷新或转到页面时,它崩溃了。控制台中的这些错误
页面仅在构建模式下崩溃。 在开发模式下很好。 我试图改变条件(加载等),但没有任何改变。
任何帮助,将不胜感激。 谢谢!
似乎问题不在于配置文件,而在于用户 _id。 最初,在您的 Profile 组件的第一次渲染中,用户是 null,因此您会收到 null 的错误_id。
尝试检查用户是否存在,然后渲染配置文件。 就像在 Profile.js 中一样
if(!user){
return null
}
return (
<Fragment>
// yor rest code
</Fragment>
此外,在使用 console.log 加载页面后,检查配置文件的用户属性是否出现 null。
我不确定,但您可以验证以避免第一个错误,我的意思是“_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>;
statusText 错误是因为您在profiles.js 中的try catch 中存在错误,并且当您要调度PROFILE_ERROR 操作时,您正尝试从err.response.statusText 访问statusText,但err.response 未定义。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.