如何在App启动时使用Redux启动抓取?

时间:2019-03-06 01:53:52

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

设置一个简单的通知计数器后。我想在应用开始时获取通知,以显示收到了多少通知。

这是配置: 减速器:

index.js

import { combineReducers } from "redux";
import posts from "./posts";
import filteredPosts from "./filteredPosts";
import notifications from "./notifications";

export default combineReducers({
  posts,
  filteredPosts,
  notifications
});

notification.js

import * as types from "../actions/types";
const initialState = [];

export default (state = initialState, action) => {
  switch (action.type) {
    case types.LOAD_NOTIFICATIONS:
      return action.notifications;
    default:
      return state;
  }
};

动作

type.js

export const FILTERED_POST = "FILTERED_POST";
export const LOAD_POSTS = "LOAD_POSTS";
export const LOAD_NOTIFICATIONS = "LOAD_NOTIFICATIONS";

notification.js

import * as types from "./types";
import { fetchNotifications } from "../service/";

export const getNotifications = auth_token => dispatch =>
  fetchNotifications(auth_token)
    .then(res => {
      return res.json();
    })
    .then(data => {
      dispatch({
        type: types.LOAD_NOTIFICATIONS,
        notifications: data.notifications
      });
    })
    .catch(err => {
      console.log(err);
    });

和服务

index.js

import { apiEndpoint } from "./config";

export const fetchPosts = auth_token =>
  fetch(`${apiEndpoint}posts`, {
    method: "GET",
    headers: {
      Accept: "application/json",
      "Content-Type": "application/json",
      Access: auth_token
    }
  });

export const fetchNotifications = auth_token =>
  fetch(`${apiEndpoint}notifications`, {
    method: "GET",
    headers: {
      Accept: "application/json",
      "Content-Type": "application/json",
      Access: auth_token
    }
  });

apiEndpoint是api地址 因此,在配置了通知标志组件并将其添加到路由器后,该应用将加载帖子,因为它是主屏幕,而不是通知。

检查一下,我将通知徽章组件放置为要首先加载的主屏幕,但仍未收到通知。因此,请有人可以说明如何在应用开始时或之前或之后立即获取使用redux的信息?

export const Logged = createBottomTabNavigator(
  {
    Notification: {
      screen: Notification,
      navigationOptions: {
        tabBarLabel: "Notification",
        tabBarIcon: () => {
          <NotificationIcon />;
        }
      }
    },

1 个答案:

答案 0 :(得分:1)

好几件事可能是错误的,首先,我将使用postman之类的工具检查端点的响应,如果响应是您期望的,那么我建议创建一个根组件,例如AppComponent,在其中,您可以在componentDidMount中使用mapDispatchToProps

调度getNotifications操作