【问题标题】:String is undefined when trying to find its length尝试查找其长度时字符串未定义
【发布时间】:2018-10-29 07:15:31
【问题描述】:

我在 Ignite 2.0 中使用 redux-form。我正在尝试验证这些值,但是每当我尝试查找字符串的长度时,它都会给我 String is undefined

这是我的组件

import React, { Component } from "react";
import { Field, reduxForm } from "redux-form";
import {
  Container,
  Content,
  Text,
  Button,
  View,
  Item,
  Input
} from "native-base";
import { StackNavigator } from "react-navigation";

const validate = value => {
  const error = {};
  error.name = "";
  error.password = "";
  const { name, password } = value;
  if (name === "undefined" || name === "") {
    error.name = "Empty";
  }
  if (password === "undefined" || password.length < 8) {
    error.password = "too short";
  }
  console.log("error", error);
};

class SignupForm extends Component {
  renderInput({
    input,
    label,
    placeholder,
    type,
    meta: { touched, error, warning }
  }) {
    var hasError = false;
    if (error !== undefined) {
      hasError = true;
    }
    return (
      <Item error={hasError}>
        <Input {...input} placeholder={placeholder} type={type} />
        {hasError ? <Text>{error}</Text> : <Text />}
      </Item>
    );
  }
  render() {
    const { handleSubmit } = this.props;

    return (
      <Container>
        <Content>
          <Field
            name="name"
            component={this.renderInput}
            label="Name"
            placeholder="Name"
            type="text"
          />
          <Field
            name="password"
            component={this.renderInput}
            placeholder="Password"
            label="Password"
            type="password"
          />
          <Button type="submit" onPress={handleSubmit}>
            <Text>Submit</Text>
          </Button>
        </Content>
      </Container>
    );
  }
}

export default reduxForm({
  form: "SignupForm",
  validate
})(SignupForm);

password.length 不断抛出错误 TypeError:password is undefined 谁能告诉我我做错了什么或者我错过了什么。

谢谢

【问题讨论】:

  • 试试if (!password &amp;&amp; password.length &lt; 8)

标签: react-native react-redux react-native-android redux-form


【解决方案1】:
if (password === "undefined" || password.length < 8) {
    error.password = "too short";
  }

这里,替换 "undefined" 不带双引号,undefined,因为 undefined 是一个原始值。

【讨论】:

    【解决方案2】:

    以这种方式检查undefined

    if (!password && password.length < 8)
    

    【讨论】:

      【解决方案3】:

      if (password === "undefined" || password.length < 8) { error.password = "too short"; }

      这里你应该做一个通用检查,检查!password || password.length &lt; 8 这样你也可以处理nullundefined 的情况。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2023-04-01
        • 2017-06-13
        • 2013-05-03
        • 1970-01-01
        • 2019-12-21
        • 1970-01-01
        • 2018-01-03
        • 1970-01-01
        相关资源
        最近更新 更多