【发布时间】:2019-03-07 23:17:53
【问题描述】:
我一直在使用 react-native 和 redux 有一段时间了,当道具发生变化时我学会调用动作的方式是使用 componentWillReceiveProps,但是当我使用它时,我需要在 if 和有时它之间传递如果出错了,那么我需要添加更多的东西来防止它。
这是我做过的一个例子。我知道这不是最好的方法,但这是我能想到的。
componentWillReceiveProps(newProps) {
if(Object.keys(newProps.selected_product).length > 0) {
if(Object.keys(this.props.current_location).length > 0 || Object.keys(newProps.current_location).length > 0) {
this._handleNextPage(2);
this.props.verifyProductById(newProps.selected_product, newProps.current_location, this.props.token);
} else {
this.props.statusScanner(false);
this._handleNextPage(1);
}
} else if(Object.keys(newProps.historic_product_confirm).length > 0) {
if(newProps.historic_product_confirm.location._id == newProps.current_location._id)
this.props.handleModalConfirmPrice(!this.props.modal_confirmPrice_status)
} else if(newProps.scanResult != "") {
this.props.statusScanner(false);
if(Object.keys(newProps.current_location).length > 0) {
this._handleNextPage(2);
} else {
this._handleNextPage(1);
}
} else {
this._handleNextPage(0);
}
}
我需要的是一种在道具发生变化时调用我的动作的健康方式。
编辑: 这里我有完整的 OfferScene 和一个动作文件示例:
优惠场景: https://gist.github.com/macanhajc/0ac98bbd2974d2f6fac96d9e30fd0642
UtilityAction: https://gist.github.com/macanhajc/f10960a8254b7659457f8a09c848c8cf
【问题讨论】:
-
您必须具有导致这些属性发生变化的操作,例如 selected_product、history_product_confirm、scanResult 等。您可以将逻辑从操作发送的位置放置,例如用户操作或 API 结果。但是当您的应用程序/组件扩展时,上面指定的代码会很混乱。
-
尽量将问题分解为多个组件,这将有助于编写更清晰和可扩展的代码。
-
您能否发布您的示例
actions或您如何处理 api? -
@Goldy 我已经这样做了,但在这种情况下,代码来自场景,我需要更改 currentPage 以在组件之间导航,并且由滚动视图控制。
-
@PritishVaidya 我现在已经发布了完整的场景和动作文件。
标签: node.js reactjs react-native redux react-redux