我需要一些建议或最佳实践,在React Native + Redux环境中,当用户触发事件时如何参数化我需要调用的URL的前缀。
这是我到目前为止的一个哑巴版本:
import { connect } from "react-redux";
import actions from "../actions/actions";
import MyWidget from "../components/MyWidget";
export const mapStateToProps = state => {
return {
itemDetails: state.itemDetails
};
};
const pushItem = (dispatch, itemDetails) => {
fetch("http://xxx.xxx.xxx.xxx:xxxx/myapp/rest/item/" + itemDetails.id, {
method: "PUT",
body: itemDetails
})
.then(response => {
dispatch(actions.hideSpinner());
})
.catch(error => {
console.log(error);
dispatch(actions.hideSpinner());
});
};
const mapDispatchToProps = dispatch => {
return {
saveItem: itemDetails => {
dispatch(actions.showSpinner());
pushItem(dispatch, itemDetails);
}
};
};
const MyWidgetCtrl = connect(mapStateToProps, mapDispatchToProps)(MyWidget);
export default MyWidgetCtrl;
在这里,当用户点击按钮时,将调用saveItem函数。这很好用,但我的问题是http://xxx.xxx.xxx.xxx:xxxx/myapp部分是硬编码的,我希望它来自我的应用程序的设置。我在考虑在启动时使用AsyncStorage提取设置并将其放入Redux存储中,然后调整上面的代码以从状态获取URL前缀;但问题是mapDispatchToProps函数不会将redux状态作为参数接收,因此这将不起作用。
对于如何解决这个问题,有什么建议吗?
编辑:请注意,我事先不知道API的url前缀,所以我不能在编译时将其放入配置文件中。这实际上是由用户在第一次使用应用程序时在提示符中键入API前缀。
发布于 2017-09-07 15:33:39
你可以使用react-native-config npm模块在支持iOS和Android的React Native中将配置变量暴露给你的javascript代码。
API_URL =通过‘app.import -native- Config’从您的反应配置中定义的http://xxx.xxx.xxx.xxx:xxxx/myapp
Config.API\_URL/itemDetails.id
,{ method:"PUT",body: itemDetails })如果API前缀被作为用户的输入,那么它可以在state/redux存储中维护,并且您可以拥有单个http实用程序,该实用程序可以作为应用程序的所有http调用的网关,并且在其中您可以从存储中访问道具。
https://stackoverflow.com/questions/46090162
复制相似问题