te')); return $arr; } /* 遍历用户所有主题 * @param $uid 用户ID * @param int $page 页数 * @param int $pagesize 每页记录条数 * @param bool $desc 排序方式 TRUE降序 FALSE升序 * @param string $key 返回的数组用那一列的值作为 key * @param array $col 查询哪些列 */ function thread_tid_find_by_uid($uid, $page = 1, $pagesize = 1000, $desc = TRUE, $key = 'tid', $col = array()) { if (empty($uid)) return array(); $orderby = TRUE == $desc ? -1 : 1; $arr = thread_tid__find($cond = array('uid' => $uid), array('tid' => $orderby), $page, $pagesize, $key, $col); return $arr; } // 遍历栏目下tid 支持数组 $fid = array(1,2,3) function thread_tid_find_by_fid($fid, $page = 1, $pagesize = 1000, $desc = TRUE) { if (empty($fid)) return array(); $orderby = TRUE == $desc ? -1 : 1; $arr = thread_tid__find($cond = array('fid' => $fid), array('tid' => $orderby), $page, $pagesize, 'tid', array('tid', 'verify_date')); return $arr; } function thread_tid_delete($tid) { if (empty($tid)) return FALSE; $r = thread_tid__delete(array('tid' => $tid)); return $r; } function thread_tid_count() { $n = thread_tid__count(); return $n; } // 统计用户主题数 大数量下严谨使用非主键统计 function thread_uid_count($uid) { $n = thread_tid__count(array('uid' => $uid)); return $n; } // 统计栏目主题数 大数量下严谨使用非主键统计 function thread_fid_count($fid) { $n = thread_tid__count(array('fid' => $fid)); return $n; } ?>javascript - Where to apply my moment() function in a react component? - Stack Overflow
最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - Where to apply my moment() function in a react component? - Stack Overflow

programmeradmin3浏览0评论

I am trying to do a clock ponent, simply to give the date and time in local format in a webpage. I imported MomentJS using the mand line npm i moment --save in my webpack environment. Next I wrote this in my Clock.jsx ponent (mostly based on the React example on the website).

import React from 'react';
import Moment from 'moment';

export default class Clock extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      dateTimestamp : Date.now()
    };
  }
  tick = () => {
    this.setState({dateTimestamp: this.state.dateTimestamp + 1});
    console.log('tick');
  }
  ponentDidMount() {
    this.interval = setInterval(this.tick, 1000);
  }
  ponentWillUnmount() {
    clearInterval(this.interval);
  }
  render() {
    const date = this.state.dateTimestamp;
    return(
      <div className="clock"> Heure locale : {date}</div>
    );
}

}

Doing this the timestamp incremented correctly. However, when passing a new state element in the object, the first value (based on Date.now() ) is calculated in the constructor but for each tick, only the timestamp is incrementing the formatted date is stuck on its first value. Here is the code.

import React from 'react';
import Moment from 'moment';

export default class Clock extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      dateTimestamp : Date.now(),
      dateFormatted : Moment(Date.now()).toString()
    };
  }
  tick = () => {
    this.setState({dateTimestamp: this.state.dateTimestamp + 1});
    console.log(this.state.dateTimestamp);
    this.setState({dateFormatted: Moment(this.state.dateTimestamp).toString()});
    console.log(this.state.dateFormatted);
  }
  ...
  render() {
    const date = this.state.dateFormatted;
    return(
      <div className="clock"> Heure locale : {date}</div>
    );
}

}

Does anyone could explain help me solving this issue but above all tell me what is going wrong with my piece of code?

Thanks

UPDATE: In the end my use of moment was not appropriate, even if I cannot figure out why it would not work this way. Find below my correct implementation to have the date and time refreshed every seconds.

import React from 'react';
import Moment from 'moment';

export default class Clock extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      dateFormatted : Moment().locale('fr').format('dddd Do MMMM YYYY HH:mm:ss').toString()
    };
  }
  tick = () => {
    this.setState({
      dateFormatted : Moment().locale('fr').format('dddd Do MMMM YYYY HH:mm:ss').toString()
    });
  }
  ponentDidMount() {
    this.interval = setInterval(this.tick, 1000);
  }
  ponentWillUnmount() {
    clearInterval(this.interval);
  }
  render() {
    const date = this.state.dateFormatted;
    return(
      <div className="clock"> Date (locale) : {date}</div>
    );
  }
}

This also "solves" the anti pattern issue exposed below (different cross-dependant setState() call). I would need the timestamp for any other reason but I will find a workaround.

I am trying to do a clock ponent, simply to give the date and time in local format in a webpage. I imported MomentJS using the mand line npm i moment --save in my webpack environment. Next I wrote this in my Clock.jsx ponent (mostly based on the React example on the website).

import React from 'react';
import Moment from 'moment';

export default class Clock extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      dateTimestamp : Date.now()
    };
  }
  tick = () => {
    this.setState({dateTimestamp: this.state.dateTimestamp + 1});
    console.log('tick');
  }
  ponentDidMount() {
    this.interval = setInterval(this.tick, 1000);
  }
  ponentWillUnmount() {
    clearInterval(this.interval);
  }
  render() {
    const date = this.state.dateTimestamp;
    return(
      <div className="clock"> Heure locale : {date}</div>
    );
}

}

Doing this the timestamp incremented correctly. However, when passing a new state element in the object, the first value (based on Date.now() ) is calculated in the constructor but for each tick, only the timestamp is incrementing the formatted date is stuck on its first value. Here is the code.

import React from 'react';
import Moment from 'moment';

export default class Clock extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      dateTimestamp : Date.now(),
      dateFormatted : Moment(Date.now()).toString()
    };
  }
  tick = () => {
    this.setState({dateTimestamp: this.state.dateTimestamp + 1});
    console.log(this.state.dateTimestamp);
    this.setState({dateFormatted: Moment(this.state.dateTimestamp).toString()});
    console.log(this.state.dateFormatted);
  }
  ...
  render() {
    const date = this.state.dateFormatted;
    return(
      <div className="clock"> Heure locale : {date}</div>
    );
}

}

Does anyone could explain help me solving this issue but above all tell me what is going wrong with my piece of code?

Thanks

UPDATE: In the end my use of moment was not appropriate, even if I cannot figure out why it would not work this way. Find below my correct implementation to have the date and time refreshed every seconds.

import React from 'react';
import Moment from 'moment';

export default class Clock extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      dateFormatted : Moment().locale('fr').format('dddd Do MMMM YYYY HH:mm:ss').toString()
    };
  }
  tick = () => {
    this.setState({
      dateFormatted : Moment().locale('fr').format('dddd Do MMMM YYYY HH:mm:ss').toString()
    });
  }
  ponentDidMount() {
    this.interval = setInterval(this.tick, 1000);
  }
  ponentWillUnmount() {
    clearInterval(this.interval);
  }
  render() {
    const date = this.state.dateFormatted;
    return(
      <div className="clock"> Date (locale) : {date}</div>
    );
  }
}

This also "solves" the anti pattern issue exposed below (different cross-dependant setState() call). I would need the timestamp for any other reason but I will find a workaround.

Share Improve this question edited Jan 10, 2016 at 12:58 AtoM_84 asked Jan 5, 2016 at 21:21 AtoM_84AtoM_84 1451 gold badge3 silver badges11 bronze badges 1
  • update the state for your formated date in ponentWillUpdate() – Mike Boutin Commented Jan 5, 2016 at 21:25
Add a ment  | 

2 Answers 2

Reset to default 8

@KrzysztofSztompka is correct, but I would add that maintaining two separate state variables to represent the current date as a number and as a formatted string is an antipattern. Derived state variables (i.e., state variables that can be calculated using another state variable) increases the responsibility on the developer to always keep the two state variables in sync. That may not seem too difficult in this simple example, but it can bee more difficult in larger, more plicated ponents/apps. Instead, it is generally considered better practice to maintain one source of truth and calculate any derived values on the fly as you need them. Here's how I would apply this pattern to your example.

import React from 'react';
import Moment from 'moment';

export default class Clock extends React.Component {

  constructor(props) {
    super(props);
    this.state = {
      dateTimestamp : Date.now()
    };
    this.tick = this.tick.bind(this);
  }

  tick() {
    this.setState({
      dateTimestamp: this.state.dateTimestamp + 1
    });
  }

  ponentDidMount() {
    this.interval = setInterval(this.tick, 1000);
  }

  ponentWillUnmount() {
    clearInterval(this.interval);
  }

  render() {
    // Calculate the formatted date on the fly
    const date = Moment(this.state.dateTimestamp).toString();
    return(
      <div className="clock"> Heure locale : {date}</div>
    );
  }

}

change your tick function to this:

tick = () => {
  var timestamp = this.state.dateTimestamp + 1;
  this.setState({
    dateTimestamp: timestamp,
    dateFormatted: Moment(timestamp).toString()
  });
}

This is because from docs :

setState() does not immediately mutate this.state but creates a pending state transition. Accessing this.state after calling this method can potentially return the existing value.

Therefore in your next setState call it use old value. My proposition change this two values at once.

发布评论

评论列表(0)

  1. 暂无评论