this.setState () не работает должным образом в собственном ответе

Я полностью понимаю, как функция this.setstate () работает в реакции, но с утра я борюсь с ошибкой, которую использую собственный календарь wix react в моей деятельности. onDayPress я вызываю функцию, которая получает дату в качестве аргумента и обновляет мой атрибут состояния "startDate", используя this.setState ({startDate: day}), но значение состояния никогда не изменяется и остается '' (пустая строка в моей консоли отладки)

Ниже приведен мой полный код класса.

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;

Одна вещь, которую я обнаружил, - это когда я снова выбираю дату, переменная состояния показывает старое состояние вместо нового состояния.


person IO Devs    schedule 18.12.2019    source источник
comment
используйте this.state = {startDate: '', endDate: '',};   -  person dineshkashera    schedule 18.12.2019
comment
я не понял, где?   -  person IO Devs    schedule 18.12.2019
comment
Что печатает console.log('Selected Day = ', day);?   -  person ravibagul91    schedule 18.12.2019
comment
он печатает объект дня {год: 2019, месяц: 12, день: 12, отметка времени: 1576108800000, dateString: 2019-12-12} год: 2019 месяц: 12 день: 12 отметка времени: 1576108800000 dateString: 2019-12-12   -  person IO Devs    schedule 18.12.2019
comment
Запуск вашего класса, в котором вы пишете state = {}. вам нужно написать внутри конструктора, используя это ключевое слово. как этот конструктор (реквизит) {супер (реквизит); this.state = {Дата начала: '', Дата окончания: '',}; }   -  person dineshkashera    schedule 18.12.2019
comment
подобный конструктор инициализации не важен. Я инициализировал свое состояние следующим образом: state = {startDate: '', endDate: '',};   -  person IO Devs    schedule 18.12.2019
comment
это задержки в обновлении моего состояния, хотя я использую обратный вызов после setstate   -  person IO Devs    schedule 18.12.2019
comment
Вы можете это попробовать? onDayPress = {this.dayPressed}   -  person Sreeram Padmanabhan    schedule 18.12.2019
comment
как я получу доступ к выбранной мной переменной дня. ты не понимаешь проблемы, я думаю   -  person IO Devs    schedule 18.12.2019
comment
Можете ли вы попробовать с инициализацией состояния внутри конструктора   -  person Pratap Tengale    schedule 19.12.2019


Ответы (1)


Я думаю, вы можете использовать метод async в своем коде:

async fun()=>{

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

Может быть, это будет вам полезно :)

person AkAk    schedule 19.12.2019