为什么不调用componentWillReceiveProps?

时间:2018-04-19 13:49:52

标签: reactjs

在孩子时,我需要听父母改变的状态,我试着这样做:

儿童

  File "<ipython-input-437-c6c16f08fe15>", line 1
    for k,(value,*names) in vars.items():
                 ^
SyntaxError: invalid syntax

然后,在父母中,我将孩子添加为:

class deleteDriverAlert extends Component {

    constructor(props) {
        super(props);

        this.state = {
          show: false
        };
      }

      componentWillReceiveProps(nextProps) {
        console.log("componentWillReceiveProps . . . . .");
        this.setState({ show: nextProps.dataset.showDeleteAll });  
      }

    render() {

        return (
            <SweetAlert
            warning
            showCancel
            confirmBtnText="Yes, delete it!"
            confirmBtnBsStyle="danger"
            cancelBtnBsStyle="default"
            title="Are you sure?"

            onConfirm={this.props.dataset.onConfirm}
            onCancel={this.props.dataset.onCancel}
            show={this.state.show}
            >
            You will not be able to recover this imaginary file!
            </SweetAlert>
        );
    }
}

export default deleteDriverAlert;

现在,虽然我确实更改了父级的属性状态<deleteDriverAlert data-showDeleteAll={this.state.show_delete_all} data-onConfirm={this.deleteDriver} data-onCancel={this.onCancelDelete} /> ,但未在子级调用show_delete_all

有什么想法吗?

2 个答案:

答案 0 :(得分:1)

首先,您不需要将道具设置为子组件的状态,以便能够动态使用它们。问题很可能与您更改父级中的状态的方式有关。

以下是您尝试做同样事情的简单示例:

Parent组件有自己的状态和一个更改它的方法,它绑定到父上下文并用按钮翻转。然后状态作为道具传递给孩子:

import React, { Component } from 'react';
import Child from './Child';

class Parent extends Component {

  constructor(props) {
    super(props);
    this.state = { show: false };
    this.flipShow = this.flipShow.bind(this);
  }

  flipShow(){
    this.setState({show: !this.state.show})
  }

  render() {
    return (
      <div>
        <p>Parent</p>
        <button onClick={this.flipShow}>Show</button>
        <Child show={this.state.show} />
      </div>
    );
  }
}

export default Parent;

然后孩子只需通过道具。注意:在下面的示例中,componentWillReceiveProps是不必要的,但我只是把它放在那里以表明它确实触发了这个设置。

import React, { Component } from 'react';
import SweetAlert from './SweetAlert';

class Child extends Component {
  componentWillReceiveProps(nextProps){
    console.log("receiving new props");
  }
  render() {
    return (
      <SweetAlert
        show={this.props.show}
      />
    );
  }
}

export default Child;

TL; DR 如果componentWillReceiveProps没有触发,那么父组件的问题以及设置prop值而不是子组件的方式就会出现问题。

答案 1 :(得分:0)

我可能错了,但我不认为当父组件改变状态时,react会重新呈现子组件,这是有道理的,因为状态是特定于该组件的本地事物。但是,由于您没有使用状态管理库,因此在这种情况下使用新的React Context API更有意义,将更改的数据传递给Child组件,它看起来非常简单

https://reactjs.org/docs/context.html