React组件构造函数和组件WillReceiveProps中的常见代码



我通常会在使用状态feact react组件时出现这种情况。

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

最初安装组件以及道具更新时,我想这样做,我最终得到了这样的样板代码:

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);
    

第一个选项实际上是第二个的剥离版本。

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

相关内容

最新更新