reactjs - 状态更新时不会触发useEffect
问题描述
我有一个 useEffect 钩子,它应该在 currentUser 的状态变化时触发。然而,它似乎会触发一次或两次,但在刷新时 currentUser 值变为 null 并且只有有时 useEffect 不会更新,所以我丢失了我的应用程序所依赖的数据。我的 api 调用中依赖于 currentUser 的数据最初显示但随后被删除。
const currentUser = props.currentUser || {};
const isPccIntegrated = isPCCUser(currentUser);
useEffect(() => {
some api calls...
loadEntries([]);
}, [props.currentUser]);
const loadEntries = async function(base, token){
let result = await api.UserRecords.chart(userID, token);
if (result.pageToken) {
// another page of entries exist, load the next page
loadEntries(base.concat(result.items), result.pageToken);
} else {
// received last page of entries
let allEntries = base.concat(result.items);
if (isPccIntegrated) {
try {
// for PCC integrated patients, pull any progress note from PCC and add into the chart
const pccNotes = await api.PCC.progressNotes(userID);
....
}
}....
const mapStateToProps = (state) => ({
userID: state.router.location.pathname.split("/").pop(),
currentUser: state.common.currentUser,
});
这表现为我的loadEntries
函数崩溃,因为它依赖于 currentUser 对象。所以 currentUser 缺少标志为isPCCIntegrated
false 并且它停止了我的功能。
解决方案
代替 mapStateToProps 使用 react-redux 钩子 useSelector 来访问您的状态,然后将其放入 useEffect 依赖数组中代替 [props.currentUser]。更新后,您的 useEffect 将触发。
const currentUser = useSelector(state => state.common.currentUser)
useEffect(() => {
some api calls...
loadEntries([]);
}, [currentUser]);
推荐阅读
- vb.net - 如何在按钮标签/文本中插入带圆圈的数字,vb.net
- python - 如何逐行迭代多个数据帧并修改其中一个
- postgresql - GraphQL - 将 JSON 解析为 graphql 类型数组以支持批量查询
- javascript - Angular 模板中可观察对象上的 ObjectUnsubscribedErrorImpl
- python - smtplib.SMTPNotSupportedError:服务器不支持 SMTP AUTH 扩展 - 尝试通过 Django 发送电子邮件
- html - 我正在做一个学校项目,我希望我的 h1 向下移动一排,以便我的 h1 再次居中
- python - 整理数据:如何在 DataFrame 中创建将特定行的值分配到组中的列
- docker - 删除 Docker 目录中的文件后,有没有办法修复或重新安装 Docker Desktop?
- kubernetes-helm - Argo helm chart 不应用我的自定义 values.yml 文件
- memory - 将外部和内部内存用于堆