从Firebase接收数据后如何设置initialState?

时间:2019-12-18 04:11:05

标签: react-native redux react-redux redux-thunk

我来自Firebase的数据。 petData.js:

import firebase from '../fb';
import 'firebase/firestore';
import {
  FETCH_CARTS_SUCCESS,
  FETCH_CARTS_FAILURE,
  FETCHING_CARTS,
} from '../actions';

export const getData = () => {
  return dispatch => {
    dispatch(getCarts());
    return new Promise((resolve, reject) => {
      let DATA = [];
      firebase
        .firestore()
        .collection('pets')
        .get()
        .then(function(querySnapshot) {
          DATA = [];
          querySnapshot.forEach(function(doc) {
            // doc.data() is never undefined for query doc snapshots
            DATA.push(doc.data());
          });
          dispatch(getCartsSuccess(DATA));
          resolve(DATA);
        })
        .catch(err => {
          dispatch(getCartsFailure(error));
          reject(err);
        });
    });
  };
};

function getCarts() {
  return {
    type: FETCHING_CARTS,
  };
}

function getCartsSuccess(data) {
  return {
    type: FETCH_CARTS_SUCCESS,
    data,
  };
}
function getCartsFailure() {
  return {
    type: FETCH_CARTS_FAILURE,
  };
}

我的减速器FetchItem.js用于获取数据

import {
  FETCH_CARTS_SUCCESS,
  FETCH_CARTS_FAILURE,
  FETCHING_CARTS,
} from '../actions';

const initialState = {
  carts: [],
  isFetching: false,
  error: false,
};
export default function cartsReducer(state = initialState, action) {
  switch (action.type) {
    case FETCHING_CARTS:
      return {
        ...state,
        isFetching: true,
      };
    case FETCH_CARTS_SUCCESS:
      return {
        ...state,
        isFetching: false,
        carts: action.data,
      };
    case FETCH_CARTS_FAILURE:
      return {
        ...state,
        isFetching: false,
        error: true,
      };
    default:
      return state;
  }
}

文件夹Reuducer中的index.js

import {combineReducers} from 'redux';
import CartReducer from './CartReducer';
import FetchItem from './FetchItem';
const rootReducer = combineReducers({
  cartsModify: CartReducer,
  cartsData: FetchItem,
});

export default rootReducer;

cartReducer.js将数据作为initialState接收

export default function(state = {}, action) {
  switch (action.type) {
    case 'ADD_TO_CART':
      return {
        ...state,
        icon: 'shopping-basket-add',
      };

    case 'REMOVE_FROM_CART':
      return {
        ...state,
        icon: 'shopping-basket-remove',
      };
  }
  return state;
}

,然后屏幕呈现该数据Popular.js

import React, {Component} from 'react';
import {StyleSheet, FlatList, View, ActivityIndicator} from 'react-native';
import PetItem from '../components/Home/PetItem';
//import Spinner from 'react-native-loading-spinner-overlay';
import {connect} from 'react-redux';
import {bindActionCreators} from 'redux';
import {getData} from '../data/petData';
class Popular extends Component {

  componentDidMount() {
    this.props.getData();
  }
  render() {
    const {carts, isFetching} = this.props.data;

    if (isFetching) {
      return <ActivityIndicator size="large" color="orange" />;
    } else
      return (
        <View style={styles.container}>
          <FlatList
            data={carts.slice().sort((x, y) => y.count - x.count)}
            renderItem={item => {
              return (
                <PetItem
                  navigation={this.props.screenProps}
                  source1={item.item.source1}
                  source2={item.item.source2}
                  source3={item.item.source3}
                  name={item.item.name}
                  info={item.item.info}
                  price={item.item.price}
                  discount={item.item.discount}
                  id={item.item.id}
                />
              );
            }}></FlatList>
        </View>
      );
  }
}

const styles = StyleSheet.create({
  container: {flex: 1, backgroundColor: '#F5F7FA'},
});

function mapStateToProps(state) {
  return {
    data: state.cartsData,
  };
}

function mapDispatchToProps(dispatch) {
  return {
    ...bindActionCreators({getData}, dispatch),
  };
}

export default connect(mapStateToProps, mapDispatchToProps)(Popular);

我希望接收到的数据作为初始状态传递给CartReducer,以更改2屏幕的图标。谢谢

0 个答案:

没有答案