【发布时间】:2017-04-05 15:17:25
【问题描述】:
我有一个时间选择器,我想将值设置为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}
/>
【问题讨论】:
-
仅供参考:您不应该在渲染中设置状态,状态更改会触发
render(),因此您将进入一个不幸的循环。除非您使用shouldComponentUpdate处理更新。 (您目前没有) -
为什么 normStart 和 specStart 设置在 props 上而不是 state 上?如果它们在道具中,您可以使用 shouldReceiveProps 生命周期方法
-
@Dan Yea 这就是我遇到的问题,也是我试图弄清楚如何解决的问题。我尝试了多种方法,但循环仍然存在问题。
-
@pineda 我确实在我的本地代码中将它们设置为状态,希望将重点放在 This.State.Start 上。他们不会改变状态。
-
我的意思是 componentWillReceiveProps :)
标签: javascript reactjs time