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

标签 javascript reactjs time

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

我在尝试执行 if-else 语句来更新 this.state.start 的状态时遇到问题。虽然它应该正确更新值(if-else 语句应该是正确的),但 React 不允许您像我写的那样更新渲染函数中的状态。如何有条件地设置 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}
          />

最佳答案

您可以有一个设置 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
}

当您立即修改状态时甚至是必需的。

关于javascript - 在 React 中渲染组件时有条件地更新 this.state?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43235298/

相关文章:

javascript - 报告未显示在 IFrame 中

javascript - GameClosure - 过滤器错误

reactjs - 如何解决 setTimeout 的 no-undef 错误

javascript - 当 0 为 false 时如何设置此输入值 ReactJS

javascript - useEffect 清理中的执行顺序

c - 如何修复我的打印时间功能,使其不会慢 8 小时?

ios - 有没有一个好方法来检查变量在连续更改一段时间后何时停止更改其值?

mysql - 如何使用 MYSQL 将数据分成 3 个不同的时间(24 小时)框架

javascript - JS端了解Tokbox视频分辨率

javascript - 为什么总是以 Angular 弹出显示?