首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >常见DRY原理违反React Native/Redux

常见DRY原理违反React Native/Redux
EN

Stack Overflow用户
提问于 2019-02-26 06:59:08
回答 1查看 328关注 0票数 0

我似乎有一个反复出现的问题,我希望有一个我不知道的设计解决方案。

我遇到了这样一种情况,我需要从两个不同的组件中分派完全相同的东西。通常,我会将其设置为单个函数,然后在两个组件中调用该函数。问题是,如果我将这个函数(需要props.dispatch)放在其他文件中,该文件将无法访问props.dispatch。

例如。

代码语言:javascript
复制
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“代码块了吗?将逻辑从组件中提取出来并将其放在一个集中位置的最佳方法是什么?

附注:这只是这种重复的一个例子,还有其他类似的情况。

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2019-02-26 08:03:01

我认为在这里(使用react模式)消除重复最自然的方法是使用或高阶组件,或HOC。HOC是一个函数,它接受react组件作为参数,并返回一个新的react组件,用一些额外的逻辑包装原始组件。

对于您的情况,它将如下所示:

代码语言:javascript
复制
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。医生会告诉你如何补救。

票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/54876000

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档