在React中渲染组件时有条件地更新this.state?

时间:2017-04-05 15:17:25

标签: javascript reactjs time

我有一个时间选择器,我想将值设置为this.state.start。但是,this.state.start的值可能等于this.props.normalthis.props.spec,具体取决于用户是否设置了特殊小时数,如果没有,则会恢复使用正常小时数。

我遇到了尝试执行 if-else 语句以更新this.state.start状态的问题。虽然它应该正确地更新值(if-else语句应该是正确的),但是反应并不允许你更新渲染函数中的状态,就像我写的那样。如何有条件地设置this.state.start?代码如下:

class NormalHours extends React.Component {
constructor(props) {
    super(props)
    this.state = {
        start: null,
    }
}
render() {
    //Browser is very angry at this part
    if(this.props.specStart == this.props.normStart || this.props.specStart == null)
    {
        //If special hours are null or equal to normal start use normal hours
        this.setState({
           start: this.props.normStart;
        });
    }
    else
    {
        //Else the hours are different so use special hours
        this.setState({
           start: this.props.specStart;
        });
    }
    return(
    <div>
        //Using Material UI; this is rendered as a textbox
        <TimePicker
          name="StartTime"
          onChange={(e, date) => {
            this.props.onSetStartTime(Utils.convertDateToTimeString(date))
          }}
          value={this.state.start}
          />

1 个答案:

答案 0 :(得分:1)

你可以有一个设置this.start.state的功能:

class NormalHours extends React.Component {
  constructor(props) {
      super(props)
      this.state = {
          start: null,
      }
      this.setStart();
  }
  setStart = () => {
    if(this.props.specStart == this.props.normStart || this.props.specStart == null)
    {
        //If special hours are null or equal to normal start use normal hours
        this.setState({
           start: this.props.normStart;
        });
    }
    else
    {
        //Else the hours are different so use special hours
        this.setState({
           start: this.props.specStart;
        });
    }
  }
  render() {
    return(
      <div>
          //Using Material UI; this is rendered as a textbox
          <TimePicker
            name="StartTime"
            onChange={(e, date) => {
              this.props.onSetStartTime(Utils.convertDateToTimeString(date))
            }}
            value={this.state.start}
            />
        </div>
      )
    }
  }

我不太了解构造函数中的调用方法是否被视为不良实践或是否

this.state = {
  start: null
}
在您立即修改状态后,甚至需要