仅在有新数据时更新,React Native App,Redux-Socket IO?

时间:2018-02-12 15:21:25

标签: react-native socket.io redux

目标:仅在我们拥有新数据时才进行API调用,而不是在用户导航到屏幕时。

让我们说我正在处理的应用程序有两个用户可以导航到的屏幕。 Receiving Text ScreenSending Screen。每个用户也可以添加好友/粉丝。在Sending Screen上,用户可以将文本项发送给他们选择的关注者。在Receiving Text Screen上,关注者用户将在屏幕顶部看到弹出的文本项。

目前,Receiving Text Screen上的用户只能在我们进行名为fetchTexts的API调用时看到该文字项。每当用户导航到此屏幕或用户下拉刷新时,我们都会进行此调用。

class TextScreen extends Component {
  static propTypes = {
    fetchTexts: PropTypes.func,
  };

constructor(props) {
  super(props);
  this.state = {
    refreshing: false,
  };
}

componentDidMount() {
  textsGATracker();
  this.props.fetchTexts(this.props.userId);
}

_onRefresh() {
  this.setState({ refreshing: true });
  // when the screen is pulled down, fetchTexts
  this.props.fetchTexts(this.props.userId);
  this.setState({ refreshing: false });
}

const mapStateToProps = (state) => {
  return {
    texts: state.texts_reducer.texts,
    userId: state.user_reducer.userId,
    textsReceived: state.texts_reducer.textsReceived,

  };
};

const mapDispatchToProps = (dispatch) => {
  return {
    fetchTexts: (userId) => { dispatch(fetchTexts(userId)); },
  };
};

这些是与fetchTexts

一起发生的Redux操作
import axios from 'axios';

export const REQUEST_TEXTS_ITEMS = 'REQUEST_TEXTS_ITEMS';
export const RECEIVE_TEXTS_ITEMS = 'RECEIVE_TEXTS_ITEMS';
export const FAILED_TEXTS_ITEMS = 'FAILED_TEXTS_ITEMS';

axios.defaults.baseURL = 'nope.herokuapp.com';

/* ======= Actions to Request Texts by userId ======= */
export const requestTextsItems = userId => ({
  type: REQUEST_TEXTS_ITEMS,
  userId,
});

export const receiveRecsItems = json => ({
  type: RECEIVE_TEXTS_ITEMS,
  texts: json,
});

export const failedtextsItems = error => ({
  type: FAILED_TEXTS_ITEMS,
  infoMsg: `The API request failed - ${error}`,
});

export const fetchtexts = userId => (dispatch, getState) => {
  const AUTH_TOKEN = `Bearer ${getState().auth_reducer.bearerToken}`;
  axios.defaults.headers.common.Authorization = AUTH_TOKEN;

  dispatch(requesttextsItems(userId));
  axios.get(`/sharesTexts/${userId}`)
  .then((response) => {
    dispatch(receivetextsItems(response.data));
  }, (error) => {
    dispatch(failedtextsItems(error));
  });
};

Sending Screen上,用户选择要与其关注者分享的文字项。使用的redux操作如下所示:

export const usersCreateshareTextId = (textId, description, sharerUserId, recipientUserId) => (dispatch, getState) => {
 recipientUserId);
  const AUTH_TOKEN = `Bearer ${getState().auth_reducer.bearerToken}`;
  axios.defaults.headers.common.Authorization = AUTH_TOKEN;

  dispatch(requestUsersCreateshare(description, sharerUserId, recipientUserId));
  return axios.post(`/users/createShare/${textId}`, {
    description,
    sharerUserId,
    recipientUserId,
  })
    .then((response) => {
 response.data);
      dispatch(receiveUsersCreateshare(response.data));
    }, (error) => {
      dispatch(failedUsersCreateshare(error));
    });
};

所以我查看了websockets,现在Redux Socket IO v.1.4.0似乎是我最好的选择。看起来它主要用于商店。我的商店看起来像这样:

import { createStore, applyMiddleware, compose } from 'redux';
import { persistStore, persistReducer } from 'redux-persist';
import storage from 'redux-persist/lib/storage';
import autoMergeLevel2 from 'redux-persist/lib/stateReconciler/autoMergeLevel2';
import thunk from 'redux-thunk';
import logger from 'redux-logger';

import reducers from '../redux/reducers';

const middleware = [thunk];

const persistConfig = {
  key: 'root',
  storage,
  stateReconciler: autoMergeLevel2,
  blacklist: ['network', 'auth_reducer', 'search_reducer', 'follow_reducer', 'following_reducer',
    'followers_reducer'],
};

if (process.env.NODE_ENV === 'development') {
  middleware.push(logger);
}

const persistedReducer = persistReducer(persistConfig, reducers);

export const store = createStore(
  persistedReducer,
  compose(applyMiddleware(...middleware)),
);

export const persistor = persistStore(store);

我如何使用目前为止实现Redux Socket IO?

谢谢谢谢谢谢!

0 个答案:

没有答案