我似乎有一个我希望有一个我不知道的设计解决方案的问题。
我遇到了需要从两个不同组件中派遣完全相同的东西的情况。通常,我将其设置为一个函数,并在两个组件中调用该功能。问题是,如果我将此函数(需要props.dispatch)放在其他文件中,该文件将无法访问props.dispatch。
ex。
class FeedScreen extends Component {
.
.
.
componentWillReceiveProps(nextProps) {
let {appbase, navigation, auth, dispatch} = this.props
//This is to refresh the app if it has been inactive for more
// than the predefined amount of time
if(nextProps.appbase.refreshState !== appbase.refreshState) {
const navigateAction = NavigationActions.navigate({
routeName: 'Loading',
});
navigation.dispatch(navigateAction);
}
.
.
.
}
const mapStateToProps = (state) => ({
info: state.info,
auth: state.auth,
appbase: state.appbase
})
export default connect(mapStateToProps)(FeedScreen)
class AboutScreen extends Component {
componentWillReceiveProps(nextProps) {
const {appbase, navigation} = this.props
//This is to refresh the app if it has been inactive for more
// than the predefined amount of time
if(nextProps.appbase.refreshState !== appbase.refreshState) {
const navigateAction = NavigationActions.navigate({
routeName: 'Loading',
});
navigation.dispatch(navigateAction);
}
}
}
const mapStateToProps = (state) => ({
info: state.info,
auth: state.auth,
appbase: state.appbase
})
export default connect(mapStateToProps)(AboutScreen)
请参阅代码的类似" const navigaTeaction"块?将该逻辑从组件中拉出并将其放在一个集中位置的最佳方法是什么?
P.S。这只是这种重复的一个例子,还有其他类似的情况。
我认为在此处删除重复的最自然方法(具有反应模式)是使用或更高阶组件或HOC。HOC是将React组件作为参数的函数,并返回新的React组件,将原始组件用其他逻辑包裹。
对于您的情况,它看起来像:
const loadingAwareHOC = WrappedComponent => class extends Component {
componentWillReceiveProps() {
// your logic
}
render() {
return <WrappedComponent {...this.props} />;
}
}
const LoadingAwareAboutScreen = loadingAwareHOC(AboutScreen);
全文更详细地说明:https://medium.com/@bosung90/use-higher-order-component-intrecont-native-native-df44e634e860
在这种情况下btw:componentWillReceiveProps被弃用。文档告诉您如何补救。