React Native-SetState位置

时间:2019-04-01 11:56:15

标签: reactjs react-native

我是RN的新手,并且可能会遇到设置状态的基本问题-目前,我有以下内容-各种任务在构造函数中运行,但setState任务不起作用-我已经在componentdidmount和遇到同样的问题-有人可以解释我要去哪里了吗?

import React from 'react';
import { connect } from "react-redux";
import {View, Image, StyleSheet, Text, StatusBar, TouchableOpacity, ScrollView} from 'react-native';
import CopyrightSpiel from './util/CopyrightSpiel';
import ButtonHomeNav from './util/ButtonHomeNav';
import BlinkMe from './util/BlinkMe';
import PropTypes from 'prop-types';
import moment from 'moment';

import { withNavigation } from 'react-navigation';

class HomeView extends React.Component {

  constructor(props) {
    super(props);
    this.state = {
      loggedIn:false,
      expDateClose :false,
      expDays : 0,

    };

    console.warn('daysRem');
    let curDate= new Date();
    let expDate= new Date(this.props.user.badgeExpiry);
    if (!moment.isMoment(curDate)) {curDate = moment(curDate);}
    if (!moment.isMoment(expDate)) {expDate = moment(expDate);}
    const daysRem = expDate.diff(curDate, 'days');
    console.warn(daysRem);
    if(daysRem >= 600){
      console.warn(daysRem);
      this.setState({expDays: 15});

      console.warn(this.state.expDays);
      console.warn(this.state.expDateClose);
    }

  }





render() {

2 个答案:

答案 0 :(得分:3)

您必须记住,setState是一个异步函数,在返回状态后不会立即设置状态。您的状态发生了变化,但是在您“ console.warn”出来之后。

您可以将回调作为第二个参数传递。

this.setState({expDay: 15}, () => {console.warn(this.sate)})

https://reactjs.org/docs/react-component.html#setstate

答案 1 :(得分:1)

React.setState不同步,它使更改进入组件状态并告诉React该组件及其子级需要使用更新后的状态重新呈现。

https://reactjs.org/docs/react-component.html#setstate