【问题标题】:this.setState() not working properly in react nativethis.setState() 在本机反应中无法正常工作
【发布时间】:2020-04-10 23:28:02
【问题描述】:

我完全理解 this.setstate() 函数如何在反应中工作,但从早上开始我就在为一个错误而苦苦挣扎 我在我的活动中使用wix react native calendar。 onDayPress 我正在调用一个函数,该函数接收日期作为参数并使用 this.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;

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

【问题讨论】:

  • 请使用 this.state = { startDate: '', endDate: '', };
  • 我不明白,在哪里?
  • console.log('Selected Day = ', day); 打印什么?
  • 它打印日期对象 "{year: 2019, month: 12, day: 12, timestamp: 1576108800000, dateString: "2019-12-12"} year: 2019 month: 12 day: 12时间戳:1576108800000 日期字符串:“2019-12-12”“
  • 在你写 state = {} 的地方开始你的课程。您需要使用 this 关键字在构造函数中编写。像这个构造函数(props) { super(props); this.state = { startDate: '', endDate: '', }; }

标签: javascript reactjs react-native velo


【解决方案1】:

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

async fun()=>{

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

也许这对你有帮助:)

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2021-01-13
    • 2020-02-28
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-09-06
    • 2021-12-07
    相关资源
    最近更新 更多