【发布时间】: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