无法通过Redux获取Firestore数据

时间:2019-10-05 00:10:03

标签: reactjs firebase redux

我正在尝试使用Redux在Firestore中获取帖子数据。但是发生Actions must be plain objects. Use custom middleware for async actions.错误。我不知道为什么,但是获取动作可能会出现一些问题。

实际上,我已经意识到使用JSON API,但是Firestore在获取帖子时发生错误。

actions / index.js

export function fetchPosts() {
  return dispatch => {
    postsRef.get().then(querySnapshot => {
      querySnapshot
        .forEach(function(doc) {
          const posts = doc.data();
          return posts;
        })
        .then(posts => {
          dispatch({ type: "FETCH_POSTS", payload: posts });
        });
    });
  };
}

reducers / reducer_post.js

import _ from "lodash";
import { FETCH_POSTS, FETCH_POST } from "../actions";

export default function(state = [], action) {
  switch (action.type) {
    case FETCH_POSTS:
      return action.posts;
    case FETCH_POST:
      return { ...state, [action.payload.data.id]: action.payload.data };

    // ** ES6 is following style **
    // const post = action.payload.data;
    // const newState = { ...state };
    // newState[post.id] = post;
    // return newState;
    default:
      return state;
  }
}

components / posts_index.js

class PostsIndex extends Component {
  componentDidMount() {
    this.props.fetchPosts();
  }
  renderPosts() {
    console.log("this.props.2", this.props);
    return _.map(this.props.posts, post => {
      return (
    );
  }
}

function mapStateToProps(state) {
  return { posts: state.posts };
}

export default connect(
  mapStateToProps,
  { fetchPosts }
)(PostsIndex);

reducers / index.js

import { combineReducers } from "redux";
import PostsReducer from "./reducer_posts";
import { reducer as formReducer } from "redux-form";

const rootReducer = combineReducers({
  posts: PostsReducer,
  form: formReducer
});

export default rootReducer;

App.js

const createStoreWithMiddleware = applyMiddleware(promise)(createStore);

function App() {
  return (
    <Provider store={createStoreWithMiddleware(reducers)}>
      <BrowserRouter>
        <div>
          <Switch>
            <Route path="/posts/new" component={PostsNew} />
            <Route path="/posts/:id" component={PostsShow} />
            <Route path="/" component={PostsIndex} />
          </Switch>
        </div>
      </BrowserRouter>
    </Provider>
  );
}

1 个答案:

答案 0 :(得分:0)

import { createStore, applyMiddleware, combineReducers } from "redux";
import PostsReducer from "./reducer_posts";
import reduxThunk from "redux-thunk";
import { reducer as formReducer } from "redux-form";

const rootReducer = combineReducers({
  posts: PostsReducer,
  form: formReducer
});

const store = createStore(rootReducer, applyMiddleware(reduxThunk));
export default store;

我错过了ReduxThunk