Welcome toVigges Developer Community-Open, Learning,Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
279 views
in Technique[技术] by (71.8m points)

react 有状态组件最佳实践?

<Father>
   <Modal {...modalProps}></Modal>
</Father>
  • 页面如上,由普通页面+弹窗组件构成;
  • modal组件是个复杂的组件:

    1. 内部状态既受Father影响,又可以在Modal自身改变;
    2. Modal还需要post,get操作;
    3. Modal需要用在多个不同的Father里面;

如何设计比较优雅,既能满足子组件modal的通用性,又不需要在各个父组件中复制粘贴一大堆预处理逻辑


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

查了下资料以及antd的示例,最后方案如下:

// 父组件
import OverlieChart from './component/overlie-chart'

        <Modal
          width="860px"
          visible={overlieVisible}
          title="test"
          maskClosable={false}
          onCancel={this.cancelOverlie}
          footer={[
            <Button key="back" type="" onClick={this.cancelOverlie}>
              关闭
            </Button>,
          ]}
        >
          <OverlieChart
            loading={loading}
            dispatch={dispatch}
            casChartData={casChartData}
            {...overlieChartProps}
          />
        </Modal>

// 子组件
  componentDidMount() {
    this.fetchData()
  }

  componentDidUpdate(prevProps) {
    // 切换化合物时更新数据
    if (prevProps.id !== this.props.id) {
      this.fetchData()
    }
  }

关键点在于:

  1. modal开关的逻辑就放在父组件中;
  2. 将复杂业务封装成子组件,和普通页面一样,使用上面两个生命周期,
  3. 利用好destroyOnClose,避免重复点击请求数据。

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to Vigges Developer Community for programmer and developer-Open, Learning and Share
...