繁体   English   中英

React / Redux如何访问网络服务中的状态

[英]React/Redux how to access the state in the networkservice

我创建了一个网络服务组件来处理API调用。 我想从更新store其他组件中检索状态。 我在获取状态时遇到问题,因此我开始使用Redux,但是我以前没有使用过Redux,但仍在尝试寻找将状态传递给NetworkService 任何帮助将是巨大的,谢谢!

这是我的NetworkService.js

import RequestService from './RequestService';
import store from '../store';

const BASE_URL = 'api.example.com/';
const REGION_ID = //Trying to find a way to get the state here

// My attempt to get the state, but this unsubscribes and
// doesnt return the value as it is async
let Updated = store.subscribe(() => {
   let REGION_ID = store.getState().regionId;
}) 

class NetworkService {

    getForecast48Regional(){
        let url =`${BASE_URL}/${REGION_ID }`;
        return RequestService.getRequest(url)
    }
}

export default new NetworkService();

store.js

import {createStore} from 'redux';

const initialState = {
  regionId: 0
};
const reducer = (state = initialState, action) => {

  if(action.type === "REGIONAL_ID") {
     return {
        regionId: action.regionId
      };
    }
    return state;
}
const store = createStore(reducer);

export default store;

我的文件夹层次结构如下所示:

-App
----Components
----NetworkService
----Store

不要直接导入商店。 由于这些原因,请使用重击/传奇/任何方式。

  • NetworkService不应了解以下任何信息
  • 恶棍们只知道NetworkService和普通的redux 动作
  • 组件只知道thunk存储 (不是存储自身,而是Redux的选择器mapStateToPropsmapDispatchToProps )。
  • 商店仅知道普通的redux 动作

知道-例如import的。

//////////// NetworkService.js
const networkCall = (...args) => fetch(...) // say, returns promise

//////////// thunks/core/whatever.js
import { networkCall } from 'NetworkService'

const thunk = (...args) => (dispatch, getState) => {
  dispatch(startFetch(...args))

  const componentData = args
  // I'd suggest using selectors here to pick only required data from store's state
  // instead of passing WHOLE state to network layer, since it's a leaking abstraction
  const storeData = getState()

  networkCall(componentData, storeData)
    .then(resp => dispatch(fetchOk(resp)))
    .catch(err => dispatch(fetchFail(err)))
}

//////////// Component.js
import { thunk } from 'thunks/core/whatever'

const mapDispatchToProps = {
  doSomeFetch: thunk,
}

const Component = ({ doSomeFetch }) =>
  <button onClick={doSomeFetch}>Do some fetch</button>

// store.subscribe via `connect` from `react-redux`
const ConnectedComponent = connect(..., mapDispatchToProps)(Component)

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM