簡體   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