如何重定位Moment变量以从渲染状态

时间:2019-05-31 16:08:16

标签: javascript reactjs momentjs state

我想知道如何更好地将我暂时使用的变量存储在我的react组件中。

我已经尝试过在setState下面的构造函数中声明变量,但是这些变量是不可更改的。然后,我尝试将状态中的变量存储为键值对,但是由于其中一个值依赖于另一个值,因此它不起作用。

这是我当前的构造函数:

constructor(props) {
super(props);
this.state = {
  scooter: props.scooter,
  header: props.header,
  reservation: ""
};
}


componentWillReceiveProps(nextProps) {
this.setState({
  scooter: nextProps.scooter,
  header: nextProps.header
});
}

某些物品在componentsWillRecieveProps中也必须被调用,因为该物品会随着下一个道具而改变。

下面的变量

render() {
const reservation = this.state.scooter.state.LastAdminReservation;
var a = moment();
const c = moment(reservation.PendingDate);
const d = moment(reservation.EndDate);
const duration = d.from(c, true);
var timeSince = a.from(d, true);
const date = moment(reservation.DownloadAckDate).format("DD.MM.YYYY 
HH:mm"); 

我希望能够在返回时调用这些变量,并在下一个道具上更新var avar timeSince而不将其存储在渲染器中,因为这是一种不好的做法。谢谢!

2 个答案:

答案 0 :(得分:0)

您可以这样做(将仅用于状态的变量放入其他方法中。

constructor() {
    super();

    const a = moment();
    const c = moment(new Date());
    const d = moment(new Date());
    const duration = d.from(c, true);
    const timeSince = a.from(d, true);

    this.state = {
      name: 'React',
      timeSince
    };
  }

答案 1 :(得分:0)

尽力而为not to derive state from props。但是,如果确实需要,getDerivedStateFromProps是React 16中引入的一种更安全的方法。

componentWillReceiveProps是您应避免使用的不赞成使用的方法。

相反,您可以创建一个函数,该函数将返回所需的日期,并通过render方法进行调用。如果您担心性能,可以memoize使用该功能。 Example here

如果您使用的是Redux之类的状态管理解决方案,则还可以将该逻辑上移到选择器,然后仅将所需的数据传递到组件中。