我在React Redux项目中工作。
我的减速器就像低于
statusReducer.js
import { FETCH_STATUS } from "../firebase/types";
export default (state = false, action) => {
switch (action.type) {
case FETCH_STATUS:
return action.payload || null;
default:
return state;
}
};
我的调度员在下面
Status.js
import firebase from 'firebase/app';
import { todosRef, authRef, provider } from './firebase';
import { FETCH_STATUS, FETCH_ONESTATUS } from './types.js';
const databaseRef = firebase.firestore();
export const fetchStatus = uid => async dispatch => {
var data = [];
databaseRef.collection('status').doc(uid).collection('status').get().then((snapshot) => {
snapshot.forEach((doc) => {
var snap = doc.data();
snap.key = doc.id;
data.push(snap);
console.log(data); // I am getting values here
});
dispatch({
type: FETCH_STATUS,
payload: data,
});
});
};
我的组件如下
import React from "react";
import * as actions from './firebase/Status';
import { connect } from 'react-redux';
import { Link } from 'react-router-dom'
class Status extends React.Component {
componentWillMount() {
const { auth } = this.props;
this.props.fetchStatus(auth.uid);
};
renderStatus() {
const { status } = this.props;
const data = status ? Object.values(status) : [];
console.log(status) // I am not getting values here
}
render() {
return (
//more HTML code
);
}
}
const mapStateToProps = ({ auth, status }) => {
return {
auth,
status,
}
}
export default connect(
mapStateToProps,
actions
)(Status);
您的Status.js
文件有一些问题。你正在从firebase获取数据并尝试调度它。但问题是你的程序在从firebase获得数据之前进行了调度。因此,您可以使用JS Promise来实现这一点。也许这会有所帮助!!!
...
const request = snapshot.forEach((doc) => {
return new Promise((resolve) => {
var snap = doc.data();
snap.key = doc.id;
console.log(data); // I am getting values here
});
});
Promise.all(request).then(() => {
dispatch({
type: FETCH_STATUS,
payload: data,
});
});
...