我的组件需要一个加载微调器。我正在使用反应钩子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>
);
}
}