Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/powerbi/2.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Javascript React'中的三元运算符问题;s componentDidMount()_Javascript_Reactjs_Ternary - Fatal编程技术网

Javascript React'中的三元运算符问题;s componentDidMount()

Javascript React'中的三元运算符问题;s componentDidMount(),javascript,reactjs,ternary,Javascript,Reactjs,Ternary,我的组件中的三元运算符有问题。我创建了一个函数来检查Sun是否已启动并返回布尔值: dayTime() { const time = new Date(); const sunrise = new Date(this.state.sunrise*1000); const sunset = new Date(this.state.sunset*1000); return time > sunrise && time < sunset; } compon

我的组件中的三元运算符有问题。我创建了一个函数来检查Sun是否已启动并返回布尔值:

dayTime() {
  const time = new Date();
  const sunrise = new Date(this.state.sunrise*1000);
  const sunset = new Date(this.state.sunset*1000);
  return time > sunrise && time < sunset;
}
componentDidMount() {
  document.body.style.backgroundImage = "url(" + (this.dayTime()? day_img_cov : night_img_cov) + ")";
    }
不幸的是,三元函数不能正常工作。它始终拾取第二个图像。但是,当我使用render()内部的三元结构时,它工作正常:

render() {

  return (
    <div className="app" style={{backgroundImage: "url(" + (this.dayTime()? day_img : night_img) + ")"}}>
      ...
    </div>
}
render(){
返回(
...
}

您还没有显示完整的类,所以我不知道
这个.state.sunrise
这个.state.sunset
是从哪里来的,但我打赌在
componentDidMount
中调用
this.day()
时,它们的设置不正确

要么在构造函数中正确初始化它们,要么确保在修改它们时更新body的背景


最好的方法是你的第二个工作状态,因为它会在状态改变时自动运行-它也不会在React树之外修改DOM,这是一个很好的实践。

使用
isDaytime
作为状态,并在此基础上操作类。
day
函数甚至可以是私有的类的e(如果不使用状态变量)

js

import classnames from 'classnames'

class Wallpaper extends Component {
  state = {
    isDaytime: daytime();
  }

  render() {
    const { isDaytime } = this.state;
    return (
      <div className={classnames('bg', {
        bg__daytime: isDaytime 
        bg__sunset: !isDaytime
      })} />
    )
  }
}
.bg {
  ...
}

.bg__daytime {
  background-image: url(day_img.png);
}

.bg__sunset {
  background-image: url(night_img.png);
}

最好在渲染中使用它。要从componendDidMount操作DOM,无论如何都是反模式的。
cDM
仅在初始装载期间调用,而不是在更新期间调用。最好在
render
中移动计算。此外,
render
不会触发自身。道具或状态必须更改。因此,您还需要需要一个内部计时器来不断刷新日间值。欢迎使用SO!谢谢@Raniz!我已将我的三元运算符移动到组件的渲染部分。