Javascript 此.setState()在react native中工作不正常

Javascript 此.setState()在react native中工作不正常,javascript,reactjs,react-native,velo,Javascript,Reactjs,React Native,Velo,我完全理解react中的这个.setstate()函数是如何工作的,但从早上开始我就被一个bug困扰着 我正在活动中使用。我正在调用一个函数,该函数接收日期作为参数,并使用此.setState({startDate:day})更新我的状态属性“startDate” 但状态值从未更改,并保持为“”(调试控制台中的空字符串) 下面是我完整的课程代码 import React, {Component} from 'react'; import styled from 'styled-component

我完全理解react中的这个.setstate()函数是如何工作的,但从早上开始我就被一个bug困扰着 我正在活动中使用。我正在调用一个函数,该函数接收日期作为参数,并使用此.setState({startDate:day})更新我的状态属性“startDate” 但状态值从未更改,并保持为“”(调试控制台中的空字符串)

下面是我完整的课程代码

import React, {Component} from 'react';
import styled from 'styled-components';
import {SafeAreaView} from 'react-native';
let variables = require('../globals/theme');
import FlatBtn from '../components/flatbtn';
import {CalendarList} from 'react-native-calendars';

class DateSelector extends Component {
  state = {
    startDate: '',
    endDate: '',
  };

  dayPressed = day => {
    console.log('Selected Day = ', day);
    this.setState({startDate: day}, () => {
      console.log(this.state.startDate); // This prints empty string :(
    });
  };

  createDateArray = (startDate, endDate) => {
    console.log('My Days', typeof startDate);
    var DaysArray = [startDate.dateString];

    if (endDate === '') {
      this.SetupCalendar(DaysArray);
      return;
    }
    for (let i = 1; i < startDate.day - endDate.day; i++) {
      DaysArray.push(
        `${startDate.year}+${startDate.month}-${startDate.day + 1}`,
      );
    }
    this.SetupCalendar(DaysArray);
  };

  SetupCalendar = DaysArray => {
    console.log(DaysArray);
  };

  render() {
    return (
      <SafeAreaView style={{flex: 1}}>
        <MainScreen>
          <TopBlock>
            <ClearButton>
              <FlatBtn
                label="Clear"
                color={variables.blackColor}
                fontstyle="Avenir-Heavy"
              />
            </ClearButton>
            <CheckIn>
              {this.state.startDate ? (
                <CheckinTime>{this.state.startDate.dateString}</CheckinTime>
              ) : (
                <CheckinTime>Check In</CheckinTime>
              )}
            </CheckIn>
            <CheckOut>
              {this.state.endDate ? (
                <CheckOutTime> {this.state.endDate.dateString}</CheckOutTime>
              ) : (
                <CheckOutTime> Check Out</CheckOutTime>
              )}
            </CheckOut>
          </TopBlock>

          <CalendarList
            // Callback which gets executed when visible months change in scroll view. Default = undefined
            onVisibleMonthsChange={months => {
              console.log('now these months are visible', months);
            }}
            // Max amount of months allowed to scroll to the past. Default = 50
            pastScrollRange={10}
            // Max amount of months allowed to scroll to the future. Default = 50
            futureScrollRange={10}
            // Enable or disable scrolling of calendar list
            scrollEnabled={true}
            // Enable or disable vertical scroll indicator. Default = false
            showScrollIndicator={false}
            // Collection of dates that have to be colored in a special way. Default = {}
            // markedDates={{
            //   '2019-12-10': {
            //     startingDay: true,
            //     color: variables.accentColor,
            //     textColor: 'white',
            //   },
            //   '2019-12-11': {
            //     selected: true,
            //     color: variables.accentColor,
            //     textColor: 'white',
            //   },
            //   '2019-12-12': {
            //     selected: true,
            //     endingDay: true,
            //     color: variables.accentColor,
            //     textColor: 'white',
            //   },
            // }}
            // Date marking style [simple/period/multi-dot/custom]. Default = 'simple'
            markingType={'period'}
            onDayPress={day => {
              this.dayPressed(day);
            }}
          />
        </MainScreen>
      </SafeAreaView>
    );
  }
}

const ClearButton = styled.View`
  display: flex;
  height: 20px;
  flex-direction: row;
  padding-left: 25px;
`;

const CheckinTime = styled.Text`
  font-family: 'Avenir-Light';
  font-size: 18px;
  color: ${variables.blackColor};
`;
const CheckOutTime = styled.Text`
  font-family: 'Avenir-Light';
  font-size: 18px;
  color: ${variables.blackColor};
`;

const MainScreen = styled.View`
  display: flex;
  flex: 1;
`;
const Text = styled.Text``;

const CheckIn = styled.View`
  display: flex;
  width: 50%;
  height: 100%;
  justify-content: center;
`;
const CheckOut = styled.View`
  display: flex;
  width: 50%;
  height: 100%;
  justify-content: center;
`;

const TopBlock = styled.View`
  display: flex;
  width: 100%;
  height: 15%;
  flex-direction: row;
  border-bottom-width: 1px;
  border-color: ${variables.borderColor};
`;

export default DateSelector;
import React,{Component}来自'React';
从“样式化组件”导入样式化;
从“react native”导入{SafeAreaView};
let variables=require('../globals/theme');
从“../components/FlatBtn”导入FlatBtn;
从“react native calendars”导入{CalendarList};
类日期选择器扩展组件{
状态={
起始日期:'',
结束日期:“”,
};
dayPressed=天=>{
console.log('Selected Day=',Day);
this.setState({startDate:day},()=>{
console.log(this.state.startDate);//这将打印空字符串:(
});
};
createDateArray=(开始日期、结束日期)=>{
console.log(“我的日子”,起始日期的类型);
var DaysArray=[startDate.dateString];
如果(结束日期==''){
此。设置日历(DaysArray);
返回;
}
for(设i=1;i{
控制台日志(DaysArray);
};
render(){
返回(
{this.state.startDate(
{this.state.startDate.dateString}
) : (
登记入住
)}
{this.state.endDate(
{this.state.endDate.dateString}
) : (
退房
)}
{
log(“现在这些月份可见”,月份);
}}
//允许滚动到过去的最大月数。默认值=50
pastScrollRange={10}
//允许滚动到未来的最大月数。默认值=50
未来滚动范围={10}
//启用或禁用滚动日历列表
scrollEnabled={true}
//启用或禁用垂直滚动指示器。默认值=false
showScrollIndicator={false}
//必须以特殊方式着色的日期集合。默认值={}
//标记日期={{
//   '2019-12-10': {
//是的,
//颜色:variables.accentColor,
//textColor:'白色',
//   },
//   '2019-12-11': {
//选择:正确,
//颜色:variables.accentColor,
//textColor:'白色',
//   },
//   '2019-12-12': {
//选择:正确,
//结束日:是的,
//颜色:variables.accentColor,
//textColor:'白色',
//   },
// }}
//日期标记样式[简单/句点/多点/自定义]。默认值=“简单”
markingType={'period'}
onDayPress={day=>{
本.日(日);
}}
/>
);
}
}
const ClearButton=styled.View`
显示器:flex;
高度:20px;
弯曲方向:行;
左侧填充:25px;
`;
const CheckinTime=styled.Text`
字体系列:“Avenir Light”;
字号:18px;
颜色:${variables.blackColor};
`;
const CheckOutTime=styled.Text`
字体系列:“Avenir Light”;
字号:18px;
颜色:${variables.blackColor};
`;
const MainScreen=styled.View`
显示器:flex;
弹性:1;
`;
const Text=styled.Text``;
const CheckIn=styled.View`
显示器:flex;
宽度:50%;
身高:100%;
证明内容:中心;
`;
const CheckOut=styled.View`
显示器:flex;
宽度:50%;
身高:100%;
证明内容:中心;
`;
const TopBlock=styled.View`
显示器:flex;
宽度:100%;
身高:15%;
弯曲方向:行;
边框底宽:1px;
边框颜色:${variables.borderColor};
`;
导出默认日期选择器;

我发现的一件事是,当我再次选择日期时,状态变量会显示旧状态而不是新状态。

我认为您可以在代码中使用
异步
方法:

async fun()=>{

   ...
   await this.setState(..)
   ...
   }

也许这对你有帮助:)

请使用这个。状态={startDate:'',endDate:'',};我不明白,在哪里?什么是
console.log('Selected Day=',Day)打印?它打印日期对象“{year:2019,month:12,day:12,timestamp:157610800000,dateString:“2019-12-12”}year:2019 month:12 day:12 timestamp:157610800000 dateString:“2019-12-12”从您编写state={}的类开始。您需要使用此关键字在构造函数内部编写。类似于此构造函数(props){super(props);this.state={startDate:'',endDate:'',};}