【问题标题】:Loading state not effective in the React application (MobX)加载状态在 React 应用程序 (MobX) 中无效
【发布时间】:2021-03-30 20:50:37
【问题描述】:

我正在编写一个从 WordPress REST API 获取数据的 React 应用程序。到目前为止一切正常,但是,加载指示器没有出现。我使用 MobX 进行状态管理。我有一个 loadingInitial 可观察的。每当我开始我的行动时,我都会将此 observable 设置为 true 以进入加载状态。在操作完成必要的操作后,我将 loadingInitial 重置为 false。所以我希望在获取帖子时看到加载屏幕。但是在加载 daha 时我看到了空白页。

下面是动作代码:

    @action loadAnecdotes = async (page: number, year: number, order: string) => {
        this.loadingInitial = true
        try {
            const anecdotesHeaders = year === 0 ? await agent.AnecdotesHeaders.list() : await agent.AnecdotesHeaders.listByYear(year)
            const maxPages = anecdotesHeaders['x-wp-totalpages']
            
            if (page <= maxPages) {
                const anecdotes = year === 0 ? await agent.Anecdotes.list(page, order) : await agent.Anecdotes.listByYear(page, year, order)
                runInAction(() => {
                    this.anecdoteArray = []
                    anecdotes.forEach((anecdote, i) => {
                        this.anecdoteArray[i] = anecdote
                    })
                    this.loadingInitial = false
                })
            } else {
                runInAction(() => {
                    this.loadingInitial = false
                })
            }
            return {anecdoteArray: this.anecdoteArray, maxPages}
        } catch (error) {
            console.log(error)
            this.loadingInitial = false
        }
    }

这是我获取帖子的组件中的 useEffect:

    useEffect(() => {
        loadAnecdotes(page, year, order).then(result => {
            if (page <= result?.maxPages)
                setArray(a => [...a, ...result?.anecdoteArray!])
            setLoaded(true)
        })
    }, [loadAnecdotes, page, year, order, setLoaded, setArray])

这是我在返回帖子之前所说的:

if (loadingInitial) return <LoadingComponent content='Anecdotes loading...' />

附带说明,我的组件被设置为观察者。

我做错了什么?

【问题讨论】:

    标签: javascript reactjs loading mobx mobx-react


    【解决方案1】:

    好吧,似乎仅 loadingInitial 是不够的。我向它添加了第二个条件,即帖子数组的长度。如果为 0,则显示加载组件。它奏效了!只是这个编辑解决了这个问题:

    if (loadingInitial || !array.length) return <LoadingComponent content='Anecdotes loading...' />
    

    【讨论】:

      猜你喜欢
      • 2021-01-29
      • 2019-09-17
      • 2020-01-20
      • 1970-01-01
      • 1970-01-01
      • 2012-12-03
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多