reactjs - 使用 react useEffect 钩子和 Redux 加载微调器并且没有 useState 钩子
问题描述
我的组件需要一个加载微调器。我正在使用反应钩子useEffect
,因为我正在使用redux
,所以我不能useState
在这个组件中使用。
这是我到目前为止所得到的,它没有按预期工作。
import React, { useEffect } from 'react';
import { fetchData } from 'lib';
export default function Example(props) {
let isFree = false;
let isLoading = true;
useEffect(() => {
async function check() {
const result = await fetchData(123);
isLoading = false; // I am aware of react-hooks/exhaustive-deps
if (!result){
isFree = true; // I am aware of react-hooks/exhaustive-deps
}
}
check();
return function cleanup() {
isLoading = false;
};
})
const bookMe = ()=> {
if (isLoading) {
return false;
}
// do something
};
return (
<div
className="column has-text-centered is-loading">
<div
className={
'button is-small is-outlined ' +
( isLoading ? ' is-loading' : '')
}
onClick={bookMe}
>
Select this slot
</div>
</div>
);
}
注意:我试过useRef
了,我没有得到答案。
注意:我可以使用类组件来实现解决方案,如下所示。跟随isLoading
。
但我的问题是重写整个事情有useEffect()
和没有 useState()
import React, { Component } from 'react';
import { fetchData } from 'lib';
export default class Example extends Component {
_isMounted = false;
state = {
isFree: false,
isLoading: true
};
componentDidMount() {
this._isMounted = true;
fetchData(123).then(result => {
if (this._isMounted) {
this.setState({ isLoading: false });
}
if (!result) {
if (this._isMounted) {
this.setState({ isFree: true });
}
}
});
}
componentWillUnmount() {
this._isMounted = false;
}
bookMe = () => {
if (this.state.isLoading) {
return false;
}
// do something
};
render() {
return (
<div
className="column has-text-centered is-loading">
<div
className={
'button is-small is-outlined ' +
(this.state.isLoading ? ' is-loading' : '')
}
onClick={this.bookMe}
>select this slot</div>
</div>
);
}
}
解决方案
我正在使用 react hook useEffect 并且因为我使用的是 redux,所以我不能在这个组件中使用 useState。
实际上你可以使用 useState。
- 状态管理是艰难的,需要做出决策。如果您使用 redux,则并非不能在组件中使用状态。
- 问题是您想在哪里管理您的请求。如果您决定在组件中管理您的请求,则必须包含状态。
一般来说,Redux 更适合:
- 存储应用程序各个部分所需的状态。
- 复杂的状态管理。
let isFree = false; let isLoading = true;
在您的代码中,您没有使用 useState,但您实际上是在尝试使用状态。这是行不通的,因为每次 let 变量都会由函数新创建。
推荐阅读
- apache-kafka - 每个应用程序的 Apache Kafka 主题
- javascript - 如何在不影响质量的情况下将视频与 CSS 对齐?
- django - 在不同的应用程序中单击注销按钮时重定向到登录视图
- google-chrome - 如何在谷歌浏览器的开发者工具控制台中创建和保存文件?
- laravel - 在 Laravel Jetstream / Fortify 中将登录用户重定向到个人资料页面(启用 2 因素)?
- ios - 动态集合视图单元格大小调整无法正常工作
- hadoop - 在 HIVE 中创建数据库时权限被拒绝
- excel - VBA:转换为数字
- react-native - 当视频在 expo-video-player 上以 react native 结束时如何提醒某些东西?
- go - 使用多种方式转换十六进制值会导致不同的输出