我有一个时间选择器,我想将其值设置为 this.state.start
。但是,this.state.start
的值可能等于 this.props.normal
或 this.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/