【问题标题】:Ternary operator issue in React's componentDidMount()React 的 componentDidMount() 中的三元运算符问题
【发布时间】:2018-08-20 12:21:31
【问题描述】:

我的组件中的三元运算符有问题。我创建了一个函数来检查 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>
}

【问题讨论】:

  • 在渲染中使用会好很多。从 componendDidMount 操作 DOM 无论如何都是 react-antipattern。
  • cDM 仅在初始挂载期间调用,从不在更新期间调用。最好将计算移至render。此外,render 不会自行触发。道具或状态都必须改变。因此,您还需要一个内部计时器来不断刷新 dayTime 值。欢迎来到 SO!

标签: javascript reactjs ternary


【解决方案1】:

你还没有展示你的完整课程,所以我不知道 this.state.sunrisethis.state.sunset 来自哪里,但我敢打赌,当你在 componentDidMount 中调用 this.dayTime() 时,它们没有正确设置.

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

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

【讨论】:

  • 谢谢@Raniz!我已将三元运算符移至组件的渲染部分。
【解决方案2】:

使用isDaytime 作为状态并根据它操作类。 dayTime 函数甚至可以在类之外是私有的(如果它不使用状态变量)。

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
      })} />
    )
  }
}

css

.bg {
  ...
}

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

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

【讨论】:

    猜你喜欢
    • 2011-10-24
    • 1970-01-01
    • 1970-01-01
    • 2019-02-17
    • 2018-07-07
    • 2014-08-16
    • 1970-01-01
    • 2016-08-09
    • 2015-05-20
    相关资源
    最近更新 更多