我似乎有一个反复出现的问题,我希望有一个我不知道的设计解决方案。
我遇到了这样一种情况,我需要从两个不同的组件中分派完全相同的东西。通常,我会将其设置为单个函数,然后在两个组件中调用该函数。问题是,如果我将这个函数(需要props.dispatch)放在其他文件中,该文件将无法访问props.dispatch。
例如。
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“代码块了吗?将逻辑从组件中提取出来并将其放在一个集中位置的最佳方法是什么?
附注:这只是这种重复的一个例子,还有其他类似的情况。
发布于 2019-02-26 08:03:01
我认为在这里(使用react模式)消除重复最自然的方法是使用或高阶组件,或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-in-react-native-df44e634e860
在这种情况下,您的HOC将成为连接的组件,并将道具从redux状态向下传递到包装组件。
顺便说一句: componentWillReceiveProps是deprecated。医生会告诉你如何补救。
https://stackoverflow.com/questions/54876000
复制相似问题