【发布时间】:2019-07-14 21:04:38
【问题描述】:
componentWillReceiveProps 作为 react 16.3 版本后的警告生命周期,我正在将旧版本更新到 16.4.2
以下是我在旧版本中使用的常见做法。
在componentWillReceiveProps循环中接收action,调用this.props.xxxxActionsCreator的函数dispatch redux action来驱动自己和其他组件更新,但是16.3之后getDerivedStateFromProps是静态的,不能调用this。
请问如何更新的做法最合适?
import React from 'react';
import PropTypes from 'prop-types';
import Modal from 'antd/lib/modal';
import * as DeleteDialogActions from '../Actions/DeleteDialogActions';
export default class DeleteDialogView extends React.Component {
constructor() {
super();
this.state = {
showDialog: false
};
}
componentWillReceiveProps(nextProps) {
switch (nextProps.actionType) {
case DeleteDialogActions.SHOW_DELETE_DIALOG:
case DeleteDialogActions.HIDE_DELETE_DIALOG:
this.showDialog();
break;
case DeleteDialogActions.DELETE_ITEM_SUCCESS:
this.props.DeleteDialogActionsCreator.updateDialog();
break;
default:
break;
}
}
showDialog = () => {
this.setState({showDialog: !this.state.showDialog});
this.props.DeleteDialogActionsCreator.updateDialog();
};
handleOk = () => {
this.props.DeleteDialogActionsCreator.doDeleteItem(this.props.deleteItemId);
this.setState({showDialog: false});
};
handleCancel = () => {
this.setState({showDialog: false});
};
render() {
return (
<div>
<Modal
title="Delete"
visible={this.state.showDialog}
onOk={this.handleOk}
onCancel={this.handleCancel}
className="delete-dialog"
>
<p>Are you sure you want to delete the item with device ID {this.props.deleteItemId} ?</p>
</Modal>
</div>
);
}
}
DeleteDialogView.defaultProps = {
deleteItemId: 0
};
DeleteDialogView.propTypes = {
actionType: PropTypes.string.isRequired,
deleteItemId: PropTypes.number.isRequired,
DeleteDialogActionsCreator: PropTypes.object.isRequired,
};
【问题讨论】:
标签: reactjs react-redux