在反应中更新状态时如何立即更新道具?

时间:2019-04-03 09:19:40

标签: javascript reactjs

我正在创建一个带有父仪表板组件和子模式组件的react应用。我在另一个子组件中有一个按钮,并且从该按钮单击中获取了ID,并在“父”仪表板组件中触发了一个功能。我在该函数中设置一个状态,并将其作为道具从“父”仪表板组件发送到“子”模式组件,以打开模式并在模式主体内显示ID。 问题是,我需要单击两次以打开模型,并且需要单击两次以关闭模态。我知道我需要使用state callback方法,但不确定如何

父仪表板组件:

import ProjectModal from './projectModal';
import Card from './card';

class Dashboard extends Component {
  constructor(props) {
    super(props);
    this.state = {
      currentId: '',
      open: false
    };
  }

  handleClose = () => {
    this.setState({ open: false });
  };

  getPojectId = (projectId) => {
    this.setState({
      open: true,
      currentId: projectId
    })
  }

  render(){
    return(
      <ProjectModal
         handleOpen={this.state.open}
         handleClosed={this.handleClose}
         projectID={this.state.currentId}
      />
      <Card getCardId={this.getPojectId} />
    )
  }
}

子模式组件:

class ProjectModal extends Component {
    constructor(props) {
        super(props);
        this.state = {
            open: false,
            currentId: ''
        };
    }

    componentWillReceiveProps() {
        this.setState({
            open: this.props.handleOpen,
            currentId: this.props.projectID
        })
    }

    render() {

        return (
            <div className="projectDetailsModal">
                <Dialog
                    open={this.state.open}
                    keepMounted
                    onClose={this.props.handleClosed}
                    aria-labelledby="form-dialog-slide-title"
                    aria-describedby="form-dialog-slide-description"
                >
                    <div className="modalClose" onClick={this.props.handleClosed}>
                        <span>&times;</span>
                    </div>
                    <DialogContent>
                        <div className="centerModal">
                            <div className="projectFormHeader">ID {this.state.currentId}</div>
                        </div>
                    </DialogContent>
                </Dialog>
            </div>
        );
    }
}

3 个答案:

答案 0 :(得分:2)

您应避免使用componentWillReceiveProps,不建议使用。另一方面,将props复制到state是一种反模式,在您的代码中不需要这样做。

在您的仪表板组件中尝试以下操作:


constructor(props) {
    super(props);
    this.state = {
      currentId: '',
      open: false
    };
    this.handleClose = this.handleClose.bind(this);

并且,在您的Modal中,首先删除State,在此组件中,您不需要它的纯净状态。在此之前,请将您所有的this.state更改为this.props

答案 1 :(得分:0)

尝试使用newProps参数是什么?

componentWillReceiveProps(newProps) {
  if (newProps.handleOpen !== this.props.handleOpen) {
       this.setState({
            open: this.props.handleOpen,
            currentId: this.props.projectID
        })
  }
 }

当前值为this.props.handleOpen,新更改的值为newProps.handleOpen

答案 2 :(得分:0)

“伊尔桑切斯”是对的。另外,您不需要将“儿童模式”作为类组件,它只能是功能性的。