小编典典

componentWillRecieveProps方法无法正常运行:ReactJS

reactjs

以下子组件从其父组件接收道具。然后,使用将道具设置为自己的状态,getInitialState并使用将值渲染到相应的输入字段this.state

componentWillRecieveProps用来在子组件收到新道具时更新其状态。

最初,调用该组件时,它可以正常工作。问题是第二次通过道具时发生的,触发道具通过的相应按钮需要两次单击才能设置孩子的状态。

我可能使用componentWillRecieveProps不正确?

getInitialState: function() {
  return {
    pitch: this.props.booking.pitch,
    email: this.props.booking.email,
    firstName: this.props.booking.firstName,
    arrivalDate: this.props.booking.arrivalDate,
  }
},

componentWillReceiveProps: function (props) {
  this.setState({
    pitch: this.props.booking.pitch,
    email: this.props.booking.email,
    firstName: this.props.booking.firstName,
    arrivalDate: this.props.booking.arrivalDate,
  })
},

完整代码:

var React = require('react');

    var createReactClass = require('create-react-class');



    var ViewBooking = createReactClass({

      getInitialState: function() {

        return {

          pitch: this.props.booking.pitch,

          email: this.props.booking.email,

          firstName: this.props.booking.firstName,

          arrivalDate: this.props.booking.arrivalDate,

        }

      },



      componentWillReceiveProps: function (props) {

        this.setState({

          pitch: this.props.booking.pitch,

          email: this.props.booking.email,

          firstName: this.props.booking.firstName,

          arrivalDate: this.props.booking.arrivalDate,

        })

      },



      _handleInputChange: function(event) {

        const target = event.target;

        const value = target.type === 'checkbox' ? target.checked : target.value;

        const name = target.name;

        var partialState = {};

        partialState[name] = value;

        console.log(partialState);

        this.setState(partialState);

      },



      _handleUpdateClose: function(e) {

        this.props.updateClose();

        e.preventDefault();

      },



      _handleUpdateBooking: function (e) {

        var tempBooking = {

          pitch: this.state.pitch,

          email: this.state.email,

          firstName: this.state.firstName,

          arrivalDate: this.state.arrivalDate,

        }

        this.props.updateBooking(tempBooking);

        e.preventDefault();

      },



      _handleDelete: function (e) {

        this.props.deleteBooking();

        e.preventDefault();

      },



      render: function() {

        if (this.props.viewFormVisibility) {

                formVisibility = {"display": "block"};

            } else {

                formVisibility = {"display": "none"};

            }



        return (

            <div>

            <form style={formVisibility}>

                <h4>View Booking</h4>

                <div className="form-group row">

                  <label className="col-2 col-form-label">Pitch</label>

                  <div className="col-10">

                    <input value={this.state.pitch} onChange={this._handleInputChange} className="form-control" name="pitch" ref="inputPitch" type="number" id="example-number-input"/>

                  </div>

                </div>

              <div className="form-group row">

                <label  className="col-2 col-form-label">First Name</label>

                <div className="col-10">

                  <input value={this.state.firstName} onChange={this._handleInputChange} className="form-control" ref="firstName" name="firstName" type="text" id="example-text-input"/>

                </div>

              </div>

              <div className="form-group row">

                <label className="col-2 col-form-label">Email</label>

                <div className="col-10">

                  <input value={this.state.email} onChange={this._handleInputChange} className="form-control" ref="inputEmail" type="email"  name="email" id="example-email-input"/>

                </div>

              </div>



              <div className="form-group row">

                <label className="col-2 col-form-label">Date</label>

                <div className="col-10">

                  <input value={this.state.arrivalDate} onChange={this._handleInputChange} className="form-control" ref="arrivalDate" name="arrivalDate" type="date" id="example-date-input"/>

                </div>

              </div>

              <button type="submit" className="btn btn-primary" onClick={this._handleUpdateBooking}>Save changes</button>

              <button className="btn btn-danger" onClick={this._handleUpdateClose}>Close</button>

              <button onClick={this._handleDelete} className="btn btn-danger">Delete</button>

            </form>

          </div>

        )

      }

    })



    module.exports = ViewBooking;

阅读 259

收藏
2020-07-22

共1个答案

小编典典

我可能会错误地使用componentWillRecieveProps?

是的,因为您需要使用props.keyname(支持传递给此方法的参数),而不是this.propsin
componentWillReceiveProps

原因是,此lifecycle方法内部this.props将具有先前props值而不是新值,此lifecycle方法之后this.props将具有新props值。

根据DOC

在已安装的组件接收新道具之前,将调用componentWillReceiveProps()。如果您需要更新状态以响应道具更改(例如,将其重置),则可以比较this.props和nextProps并在此方法中使用this.setState()执行状态转换。

这是因为componentWillReceiveProps将为每个setState内部父级调用,因此在设置newprops内部子级组件之前,我们应该先比较prev值和新值,可能是在父级内部某些其他state值已更改,而不是我们传递给子级组件的值。

console.logthis.propsnewProps和检查结果。

用这个:

componentWillReceiveProps: function (newProps) {
    this.setState({
        pitch: newProps.booking.pitch,
        email: newProps.booking.email,
        firstName: newProps.booking.firstName,
        arrivalDate: newProps.booking.arrivalDate,
    })
    console.log('previous value', this.props);    //print the previous values
    console.log('new values', newProps);          //new values
},
2020-07-22