繁体   English   中英

React组件构造函数和componentWillReceiveProps中的公共代码

[英]Common code in React component constructor and componentWillReceiveProps

在使用有状态的React组件时,我经常遇到这种情况。

我需要对props进行一些操作 - 要么做一些我现在想要在render()处理,要么根据props中的值设置状态。

正如我想在组件最初安装时以及更新道具时这样做时,我最终会得到一个类似这样的样板代码:

constructor(){
    super(props)
    const modifiedProps = doSomethingWithProps(props)
        ...
    this.state = {initialState}
}

componentWillReceiveProps(nextProps) {
    const modifiedProps = doSomethingWithProps(nextProps)
         ...
    this.setState({newState})
}

doSomethingWithProps(props){
        ...
}

有没有更好的方法来做到这一点?

根据问题的评论回答,我觉得很有帮助 -

如果需要基于props完成大量工作, componentWillMount允许您在辅助函数中使用this.setState()并最小化在constructor完成的工作。 这可以清理一堆其他重复的代码。

constructor(){
    super(props)
    this.state = {initialState}
}

componentWillMount() {
    this.doSomethingWithProps(this.props);
}

componentWillReceiveProps(nextProps) {
    this.doSomethingWithProps(nextProps)
}

doSomethingWithProps(props){
    ...
    this.setState({newState})
}

为什么不在转换之后将道具传递给组件?

这可以通过以下几种方式实现:

  1. 使用一个简单的无状态容器,它可以转换道具并将它们传递给这个组件。

     export const Container = (props) => <YourComponent modifiedProp={doSomethingWithProps(props)} /> 
  2. 使用连接的组件并在mapStateToProps方法中进行转换:

     const mapStateToProps = (state, ownProps) => ({ modifiedProp: doSomethingWithProps(ownProps) }); export const ConnectedComponent = connect(mapStateToProps)(YourComponent); 

第一个选项实际上是第二个选项的精简版。

您可能还有兴趣使用选择器来计算传递给组件的派生道具。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM