完成长时间操作后更改什么组件 returns
Changing what component returns after it completes a long operation
我的组件如下所示:
export default function MyComponent(){
//long async operation
//return something that is set inside the async operation
}
由于异步操作需要一些时间,return
语句在异步任务结束之前运行,因此它 returns 不完整。
如何更改组件 returns 在随机长时间的异步操作(或承诺)结束后给我一些结果?
您必须使用状态并在异步操作结束后更新它:
export default function MyComponent(){
const [loading, setLoading] = useState();
setLoading(true);
//long async operation
setLoading(false);//this should run once the async operation has finished
//return something that is set inside the async operation
return loading ? <LoadingComponent /> : <MyView />;
}
使用状态确定数据何时为 loading/complete/failed
export default function MyComponent(){
const [loading, setLoading] = React.useState(false);
const [data, setData] = React.useState(null);
const [error, setError] = React.useState(null);
React.useEffect(() => {
setLoading(true);
longAsyncOperation()
.then((data) => {
setData(data);
})
.catch((error) => {
setError(error);
})
.finally(() => {
setLoading(false);
});
}, []);
return isLoading
? (<div>Loading</div>)
: error || !data ? (<div>{error.message}</div>)
: (<div>Complete!</div>)
}
我的组件如下所示:
export default function MyComponent(){
//long async operation
//return something that is set inside the async operation
}
由于异步操作需要一些时间,return
语句在异步任务结束之前运行,因此它 returns 不完整。
如何更改组件 returns 在随机长时间的异步操作(或承诺)结束后给我一些结果?
您必须使用状态并在异步操作结束后更新它:
export default function MyComponent(){
const [loading, setLoading] = useState();
setLoading(true);
//long async operation
setLoading(false);//this should run once the async operation has finished
//return something that is set inside the async operation
return loading ? <LoadingComponent /> : <MyView />;
}
使用状态确定数据何时为 loading/complete/failed
export default function MyComponent(){
const [loading, setLoading] = React.useState(false);
const [data, setData] = React.useState(null);
const [error, setError] = React.useState(null);
React.useEffect(() => {
setLoading(true);
longAsyncOperation()
.then((data) => {
setData(data);
})
.catch((error) => {
setError(error);
})
.finally(() => {
setLoading(false);
});
}, []);
return isLoading
? (<div>Loading</div>)
: error || !data ? (<div>{error.message}</div>)
: (<div>Complete!</div>)
}