React+react-redux项目如何在组件渲染前从Firebase拉取数据存入状态
实现方案
注意:异步Action需要你的Redux配置了
redux-thunk中间件才能正常运行,大部分React+Redux项目默认都会配置该中间件。
步骤1:定义拉取Firebase数据的Redux异步Action与对应Reducer
首先编写异步请求逻辑,拿到数据后存入Redux状态:
// action文件代码 // 定义action类型 const GROUPS_FETCH_SUCCESS = 'GROUPS_FETCH_SUCCESS' // 异步拉取groups的action export const fetchGroups = () => async dispatch => { // 替换为你实际的Firebase查询逻辑 const snapshot = await firebase.firestore().collection('groups').get() const groups = snapshot.docs.map(doc => ({id: doc.id, ...doc.data()})) // 将数据提交到reducer更新状态 dispatch({ type: GROUPS_FETCH_SUCCESS, payload: groups }) }
对应Reducer中处理数据更新,可新增加载状态优化体验:
// reducer文件代码 const initialState = { groups: [], isLoading: true } const groupReducer = (state = initialState, action) => { switch(action.type) { case GROUPS_FETCH_SUCCESS: return { ...state, groups: action.payload, isLoading: false } default: return state } }
步骤2:在mapDispatchToProps中绑定拉取方法
import { fetchGroups } from '你的action文件路径' const mapDispatchToProps = dispatch => ({ fetchGroups: () => dispatch(fetchGroups()) })
步骤3:修改组件逻辑,控制渲染时机
提供两种兼容不同React版本的写法:
写法1:类组件写法(兼容所有React版本)
import React, { Component } from 'react' class GroupsPage extends Component { // 组件挂载后立刻触发数据拉取 componentDidMount() { this.props.fetchGroups() } render() { const { groups, isLoading } = this.props // 加载中返回占位提示,避免提前执行map逻辑 if (isLoading) return <div>数据加载中...</div> return ( <div className='groups-page'> <div className='groups'> { groups.map(({id,...otherGroupProps}) => ( <GroupItem key={id} id={id} {...otherGroupProps}/> )) } </div> </div> ) } } const mapStateToProps = createStructuredSelector({ groups: selectGroups, isLoading: selectGroupsLoading // 对应reducer中的isLoading字段,自行编写对应selector即可 })
写法2:函数组件+Hook写法(React 16.8及以上版本支持)
import React, { useEffect } from 'react' const GroupsPage = ({groups, isLoading, fetchGroups}) => { // 组件挂载时执行一次数据拉取 useEffect(() => { fetchGroups() }, [fetchGroups]) if (isLoading) return <div>数据加载中...</div> return ( <div className='groups-page'> <div className='groups'> { groups.map(({id,...otherGroupProps}) => ( <GroupItem key={id} id={id} {...otherGroupProps}/> )) } </div> </div> ) }
可选简化方案
如果不需要加载态提示,也可以直接判断groups长度,空数组时返回空占位即可:
if (!groups.length) return null
内容的提问来源于stack exchange,提问作者MasterWilliams
相关产品推荐
相关产品推荐

