【问题标题】:React/Redux how to access the state in the networkserviceReact/Redux 如何访问网络服务中的状态
【发布时间】:2018-07-26 16:22:34
【问题描述】:

我创建了一个处理 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

【问题讨论】:

  • 你为什么不把你想要的值作为参数传递给getForecast48Regional
  • 问题是,一旦我收到更多的 Api 调用,我将不得不将参数传递给所有它们,并且它不会保持一致。
  • @azium 是对的,你最好尽量让 API 调用不知道 store 的形状,因为通常 API 调用只需要几个参数,而 store 包含与 UI 应用程序相关的所有信息,而不是100% 业务逻辑的东西

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


【解决方案1】:

不要直接导入 store。出于这些原因,请使用 thunks/sagas/whatever。

  • NetworkService 不应该知道下面的任何事情
  • Thunks 只知道 NetworkService 和普通的 redux actions
  • 组件只知道 thunksstore(不是 store 本身,而是 Redux 的选择器,mapStateToPropsmapDispatchToProps)。
  • Store 只知道普通的 redux actions

知道 - 例如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)

【讨论】:

  • 是的,我读过thunk,但没有完全理解,谢谢你的回答,会用这个方法。
  • 在阅读了更多关于 thunk 的内容后,我似乎需要重新调整我进行 API 调用的方式。有没有办法让NetworkService 接收状态?...我认为你的方法意味着改变整个 NetworkService
  • @SGhaleb 我已经更新了 thunk 示例。它现在符合您对 API 调用层的看法吗?
猜你喜欢
  • 2021-03-08
  • 2020-10-26
  • 2020-11-05
  • 2016-11-14
  • 2020-10-07
  • 2016-01-02
  • 2011-07-12
  • 2017-12-05
  • 2023-03-23
相关资源
最近更新 更多