【发布时间】:2019-09-06 19:07:25
【问题描述】:
编辑注意:这个提到的问题实际上并没有解决我的第一个问题,这是一个围绕第一个三元结果的额外 {} 问题。我用括号替换了它们。 Josep 使用 getTime 的解决方案我最终需要将日期等同起来。我在实时日期上使用的 Date().setHours(0,0,0,0) 等同于用户生成的日期,其中 0 为小时、分钟、秒,然后是 .getTime()
为什么hour 不能访问组件构造函数内部的const hour = this.state.date.getHours() (state date = new Date()),当我把它放在日期=== 三元中时?在 react 组件的 jsx 中,小时嵌套的三元组在它自己的时候得到小时。 new Date(this.state.year, this.state.month, this.state.day) 用作用户选择的日期,当用户选择它时设置状态 - 所以如果它等于当前的 date,我想在嵌套的三元组中渲染图像 clockbordermoon 或 clockbordersun。
我在 if 语句的渲染中尝试了嵌套三元组,但仍然无法到达 hour
{date === new Date(this.state.year, this.state.month, this.state.day) ?
{hour === 20 ||
hour === 21 ||
hour === 22 ||
hour === 23 ||
hour === 0 ||
hour === 1 ||
hour === 2 ||
hour === 3 ||
hour === 4 ? (
<img
src={clockbordermoon}
className="clockborder"
style={{
transform: `translate(-50%, -50%)rotate(${totaldegrees}deg)`
}}
alt="error"
/>
) : (
<img
src={clockbordersun}
className="clockborder"
style={{
transform: `translate(-50%, -50%)rotate(${totaldegrees}deg)`
}}
alt="error"
/>
)}
: null}
我怎样才能让hour 读取const hour = this.state.date.getHours(),这是在 div 和 imgs 之前的渲染内部?
这是我今天的第二个问题,我应该在这之后设置一段时间,对不起
完整代码(暂定):https://codesandbox.io/s/zen-dijkstra-1c31n?fontsize=14 这个组件是 src>UIConainers>Calendar>CalSlideDrawer.js,通过左上角的 logo 图标找到(如果你是在紫色屏幕上开始按收件箱图标后)
编辑(错误 Unexpected token, expected "," 在第一个小时后是因为我不需要三元的第一个结果周围的括号):
class CalSlideDrawer extends React.Component {
constructor(props) {
super(props);
this.state = {
date: new Date(),
day: new Date().getDate(),
month: +new Date().getMonth() + 1,
year: +new Date().getFullYear(),
};
}
//statefor
const monthname = Object.keys(CALENDAR_MONTHS)[
Math.max(0, Math.min(month - 1, 11))
].toUpperCase();
const weekdayname = new Date(this.state.year, this.state.month, this.state.day);
const hour = this.state.date.getHours();
return (
{date.getTime() === weekdayname.getTime() ?
(hour === 20 ||
hour === 21 ||
hour === 22 ||
hour === 23 ||
hour === 0 ||
hour === 1 ||
hour === 2 ||
hour === 3 ||
hour === 4 ? (
<img
src={clockbordermoon}
/>
) : (
<img
src={clockbordersun}
/>
)): null}
【问题讨论】:
-
为什么不直接使用
if/else块?我的经验法则是,如果三进制超过三行,它可能应该进入一个块...... -
我认为三元组的代码更少,所以如果我可以从嵌套三元组中获取变量,从它在 div 和 imgs 之前的渲染中定义,那么我会使用它,如果我不能我会再试一次,但是当我上次尝试时没有用,所以我认为问题出在小时,...或者正如 Josep 所说,也许只是因为我在使用它之前没有实例化 new Date()三元比较
-
您可能需要考虑在所有这些小时比较周围加上括号,或使用数组(例如,
[20,21,22,23,0,1,2,3,4].includes(hour))。另外,我没有太多使用 React,但我不确定你是否需要所有的花括号......最后,在大多数专业设置中,“更少的代码”排在“可理解的代码”之下。 -
我认为三元组更容易阅读,而且代码更少。我稍后会尝试/研究包括但现在我只想让它工作
标签: javascript reactjs