不变违规:应将日期或时间指定为“值”。如何使用日期选择器解决这个问题?

问题描述 投票:0回答:2

我正在尝试将日期选择器添加到使用 React-Native 中的 nativebase 创建的表单中。

但我收到错误作为不变违规:日期或时间应指定为

value

我的代码:

import React, { Component, useState, useEffect, useRef } from "react";
import {
  Container,
  Header,
  Content,
  H1,
  Text,
  Form,
  Item,
  Input,
  DatePicker,
} from "native-base";

export default function createOrder() {
  const [name, setName] = useState("");
  const [amount, setAmount] = useState("");
  const [count, setCount] = useState("");
  const [price, setPrice] = useState("");
  const [commission, setCommission] = useState("");
  const [date, setDate] = useState(new Date());
  // used to regulate when calculations are made
  const [focusedInput, setFocus] = useState(null);
  console.log(date);

  // run an effect when price, count, or amount changes
  useEffect(() => {
    // if price and count exist and user isnt changing amount, calculate amount
    if (price && count && focusedInput !== "amount") {
      setAmount((parseFloat(price) * parseFloat(count)).toString());
    }
    // if price and count exist and user isnt changing count, calculate count
    else if (price && amount && focusedInput !== "count") {
      setCount((parseFloat(amount) / parseFloat(price)).toString());
    }
  }, [price, count, amount]);
  // when amount changes, update commission and total
  useEffect(() => {
    if (isNaN(parseFloat(amount))) setCommission("");
    if (amount) setCommission((parseFloat(amount) * 0.002).toString());
  }, [amount]);

  return (
    <Container>
      <Header />
      <Content>
        <Form>
          <Item>
            <Input
              placeholder="coin name"
              onChangeText={(text) => setName(text)}
            />
          </Item>
          <Item>
            <Input
              placeholder="number of coins"
              onChangeText={(text) => setCount(text)}
              keyboardType="decimal-pad"
              value={count}
              onFocus={() => setFocus("count")}
            />
          </Item>
          <Item>
            <Input
              placeholder="Amount Invested"
              onChangeText={(text) => setAmount(text)}
              keyboardType="decimal-pad"
              value={amount}
              onFocus={() => setFocus("amount")}
            />
          </Item>

          <Item>
            <Input
              placeholder="coin price"
              onChangeText={(text) => setPrice(text)}
              keyboardType="decimal-pad"
              value={price}
              onFocus={() => setFocus("price")}
            />
          </Item>
          <Item last>
            <DatePicker
              style={{ width: 200 }}
              date={date}
              mode="date"
              placeholder="select date"
              format="YYYY-MM-DD"
              minDate="2016-05-01"
              maxDate="2017-11-01"
              confirmBtnText="Confirm"
              cancelBtnText="Cancel"
              onDateChange={(date) => setDate(date)}
            />
          </Item>
        </Form>
        <Text>Commission: {commission}</Text>
        <Text>
          Total Amount:{" "}
          {(parseFloat(commission) + parseFloat(amount)).toString()}
        </Text>
      </Content>
    </Container>
  );
}

我也检查了本机基本示例中提供的默认sample。但错误如下。

当我单击用户界面中的选择日期字段时,我收到此错误。

UI

Invariant Violation: A date or time should be specified as `value`.

This error is located at:
    in RNDateTimePicker (at DatePicker.js:94)
    in RCTView (at View.js:34)
    in View (at AppContainer.js:106)
    in RCTView (at View.js:34)
    in View (at AppContainer.js:132)
    in AppContainer (at Modal.js:220)
    in RCTView (at View.js:34)
    in View (at Modal.js:242)
    in RCTModalHostView (at Modal.js:228)
    in Modal (at DatePicker.js:80)
    in RCTView (at View.js:34)
    in View (at DatePicker.js:79)
    in RCTView (at View.js:34)
    in View (at DatePicker.js:64)
    in RCTView (at View.js:34)
    in View (at DatePicker.js:63)
    in DatePicker (at DatePickerExample.jsx:17)
    in RCTView (at View.js:34)
    in View (at ScrollView.js:1124)
    in RCTScrollView (at ScrollView.js:1260)
    in ScrollView (at ScrollView.js:1286)
    in ScrollView (at KeyboardAwareHOC.js:487)
    in KeyboardAwareScrollView (at Content.js:37)
    in RCTView (at View.js:34)
    in View (at SafeAreaView.js:41)
    in ForwardRef(SafeAreaView) (at Content.js:36)
    in Content (at connectStyle.js:392)
    in Styled(Content) (at DatePickerExample.jsx:16)
    in RCTView (at View.js:34)
    in View (at Container.js:12)
    in Container (at connectStyle.js:392)
    in Styled(Container) (at DatePickerExample.jsx:14)
    in DatePickerExample (at App.js:9)
    in App (created by ExpoRoot)
    in ExpoRoot (at renderApplication.js:45)
    in RCTView (at View.js:34)
    in View (at AppContainer.js:106)
    in RCTView (at View.js:34)
    in View (at AppContainer.js:132)
    in AppContainer (at renderApplication.js:39)
at node_modules\react-native\Libraries\LogBox\LogBox.js:148:8 in registerError
at node_modules\react-native\Libraries\LogBox\LogBox.js:59:8 in errorImpl
at node_modules\react-native\Libraries\LogBox\LogBox.js:33:4 in console.error
at node_modules\expo\build\environment\react-native-logs.fx.js:27:4 in error
at node_modules\react-native\Libraries\Core\ExceptionsManager.js:104:6 in reportException
at node_modules\react-native\Libraries\Core\ExceptionsManager.js:171:19 in handleException
at node_modules\react-native\Libraries\Core\setUpErrorHandling.js:24:6 in handleError
at node_modules\expo-error-recovery\build\ErrorRecovery.fx.js:12:21 in ErrorUtils.setGlobalHandler$argument_0
at node_modules\regenerator-runtime\runtime.js:63:36 in tryCatch
at node_modules\regenerator-runtime\runtime.js:293:29 in invoke
at node_modules\regenerator-runtime\runtime.js:63:36 in tryCatch
at node_modules\regenerator-runtime\runtime.js:154:27 in invoke
at node_modules\regenerator-runtime\runtime.js:164:18 in PromiseImpl.resolve.then$argument_0
at node_modules\react-native\node_modules\promise\setimmediate\core.js:37:13 in tryCallOne
at node_modules\react-native\node_modules\promise\setimmediate\core.js:123:24 in setImmediate$argument_0
at node_modules\react-native\Libraries\Core\Timers\JSTimers.js:130:14 in _callTimer
at node_modules\react-native\Libraries\Core\Timers\JSTimers.js:181:14 in _callImmediatesPass
at node_modules\react-native\Libraries\Core\Timers\JSTimers.js:441:30 in callImmediates
at node_modules\react-native\Libraries\BatchedBridge\MessageQueue.js:387:6 in __callImmediates
at node_modules\react-native\Libraries\BatchedBridge\MessageQueue.js:135:6 in __guard$argument_0
at node_modules\react-native\Libraries\BatchedBridge\MessageQueue.js:364:10 in __guard
at node_modules\react-native\Libraries\BatchedBridge\MessageQueue.js:134:4 in flushedQueue
at [native code]:null in flushedQueue
at [native code]:null in invokeCallbackAndReturnFlushedQueue
react-native native-base
2个回答
0
投票

当您取消选择器而不是选择新日期时,会发生这种情况,它将日期的值设置为未定义的值,解决方案是检查 onChange 函数的事件并将其设置为先前的日期状态(如果关闭),例如。

const [date, setDate] = useState(new Date())

const onChange = (event, selectedDate) => {
        setShowDate(false);

        // on cancel set date value to previous date
        if (event?.type === 'dismissed') {
            setDate(date);
            return;
        }
        setDate(selectedDate);
    };

0
投票

您可能会考虑仅在值可用时才显示选择器。

{ this.state.date != null &&
        <DateTimePicker
        testID="dateTimePicker"
        value={this.state.date}
        mode={'datetime'}
        is24Hour={false}
        onChange={this._onChange}
      />}
© www.soinside.com 2019 - 2024. All rights reserved.