[英]Loading spinner with react useEffect hook and Redux and without useState hook
I need to have a loading spinner for my component.我的组件需要一个加载微调器。 I am using react hook
useEffect
and because I am using redux
, I can't use useState
in this component.我正在使用 react hook
useEffect
并且因为我使用的是redux
,所以我不能在这个组件中使用useState
。
this is what I've got so far and it doesn't work as expected.这是我到目前为止所得到的,它没有按预期工作。
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>
);
}
Note: I tried useRef
and I didn't get the answer.注意:我试过
useRef
并没有得到答案。
Note: I can achieve the solution with class component as bellow.注意:我可以使用类组件来实现解决方案,如下所示。 Follow
isLoading
.按照
isLoading
。
But my question is rewrite the whole thing with useEffect()
and without useState()
但我的问题是用
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>
);
}
}
I am using react hook useEffect and because I am using redux, I can't use useState in this component.
我正在使用 react hook useEffect 并且因为我使用的是 redux,所以我不能在这个组件中使用 useState。
Actually you can use useState.其实你可以使用useState。
In general Redux is more appropriate for:一般来说,Redux 更适合于:
let isFree = false; let isLoading = true;
In your code your aren't using useState, but you are actually trying to use state.在您的代码中,您没有使用 useState,但您实际上是在尝试使用 state。 This can't work because each time the let variable will be newly created by the function.
这是行不通的,因为每次都会由函数新创建 let 变量。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.