如何解决向数据库发出请求时
很抱歉,因为这将是一篇很长的文章,但是我非常感谢您的帮助。我一直在努力使它工作,但是没有运气。
我正在调用数据库以获取图像,在此调用期间,我希望加载程序处于活动状态。加载程序在通话期间未显示(当我对其进行硬编码时,它可以工作)。另一个问题是<noresults />
组件。它应该在对数据库的查询返回为空时呈现。但是,此组件在api调用运行时正在呈现。
TLDR 我需要在api调用期间加载程序,但正在渲染<noresults />
组件,然后正在渲染从数据库返回的数据。
使用mongodb,express,mobx和反应。
媒体商店Mobx:
export class MediaStore {
@observable loading = true
@observable trending = []
@action setLoading = (bool) => { this.loading = bool }
@action getTrending = async (category,pageNum,input) => {
this.setLoading(true)
this.error = false
let cancel
axios({
method: 'GET',url: `http://localhost:3001/media/trending?category=${category}&page=${pageNum}&input=${input}`,cancelToken: new axios.CancelToken(c => cancel = c)
}).then(res => {
this.trending =
[...new Set([...this.trending,...res.data.creators]
.map(JSON.stringify))].map(JSON.parse)
this.setHasMore(res.data.creators.length > 0)
this.setLoading(false)
}).catch(e => {
if (axios.isCancel(e)) return
this.error = true
})
return () => cancel
}
}
MediaCards组件:
const MediaCards = inject('userStore','mediaStore')(observer((props) => {
const ref = useCreators(props.mediaStore);
const location = useLocation()
const classes = useStyles()
const { isLoggedIn,favorites } = props.userStore;
const { trending,loading } = props.mediaStore;
const { media,header,mediaCard } =
location.pathname === '/dashboard' && (!isLoggedIn || !favorites.length)
? { media: [],header: 'basic',mediaCard: false }
: location.pathname === '/dashboard'
? { media: favorites,mediaCard: true }
: { media: trending,header: 'explore',mediaCard: true }
const renderMediaCards = (media) => {
return media.map((data,i) => {
let isFavorite = favorites.some(f => data._id === f._id)
if (header === 'explore' && media.length === i + 1) {
return <MediaCard lastRef={ref} id={data._id} img={data.img} isFavorite={isFavorite} twitchName={data.twitch} key={data._id} />
}
return <MediaCard id={data._id} img={data.img} isFavorite={isFavorite} twitchName={data.twitch} key={Math.random()} />
})
}
return (
<>
<Header page={header} />
{header === 'explore' ? <CategoryBar /> : <Paper className={classes.paperTopMedia}></Paper>}
{mediaCard
? <Paper className={classes.paperMedia}>
<Grid container>
<GridList cellHeight={180} className={classes.rootMedia}>
{!trending.length && !loading && <noresults />}
{!loading && renderMediaCards(media)}
{loading && <Loading />}
</GridList>
</Grid>
</Paper>
: <EmptyCard />
}
</>
)
}))
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。