首页 > 解决方案 > 反应选择类型错误:无法读取未定义的属性“名称”

问题描述

我有一个带有句柄变化的反应选择组件,只需要更新状态

当我单击选择选项时,我收到此错误

TypeError:无法读取未定义的属性“名称”

问题在于尝试更新组状态时的反应选择。

有任何想法吗?我似乎无法弄清楚这一点,我需要在这里输入更多内容,以便我可以提交我的问题,而忽略我在下面输入的内容。我曾经和你一样是冒险家,然后我膝盖中了一箭,问我的任何一个守卫,他们会告诉你这是真的,我们都中了一箭。让我猜猜有人偷了你的糖果?

这是我下面的联系人创建组件

import React, { useState, useEffect } from 'react';
import { useDispatch, useSelector } from 'react-redux';
import PropTypes from 'prop-types';
import { toast } from 'react-toastify';
import Select from 'react-select';
import makeAnimated from 'react-select/animated';
import { createContact } from '../../actions/index';
import { Button, Form, FormGroup, Input, Label } from 'reactstrap';
import Divider from '../common/Divider';
import 'react-phone-input-2/lib/style.css';
import PhoneInput from 'react-phone-input-2';

const ContactForm = ({ hasLabel }) => {
  const dispatch = useDispatch()
  // State
  const [contact, setContact] = useState({ 
    phone_number: '',
    phone_type: 'mobile',
    group: '',        <------- this is giving error
    firstName: '',
    lastName: '',
    company: '',
    email: '',
    error: '',
    open: false})
  
  const [isDisabled, setIsDisabled] = useState(true);
  
  // Handler
   const handleSubmit = e => {
    e.preventDefault()
    dispatch(createContact(contact))
   };

  
  const handleChange = e => {
    setContact({...contact, [e.target.name]: e.target.value})
  };
  
  const groups = useSelector((state) => state.groups)
  

  useEffect(() => {
  
    setIsDisabled( !contact.phoneNumber || !contact.phoneType);
  }, [contact.phoneNumber, contact.phoneType ]);

  return ( 
  <>
    <Form onSubmit={handleSubmit}>
      
      <FormGroup>
        <Label>Enter a Number</Label>
       
        <PhoneInput 
        
            country="us"
            isValid={(value, country) => {
              if(value.match(/12345/)) {
                return 'Invalid value: '+value+', '+country.name;
              } else if (value.match(/1234/)) {
                return false
              } else {
                return true;
              }
            }}
            inputStyle={{border: 'none', font: 'caption' }}
            inputClass="w-100 font-weight-bold"
            containerClass="rounded text-sm shadow focus:outline-none focus:shadow-outline dark"
            countryCodeEditable={false}
            dropdownClass="rounded"
            preferredCountries={['us','ca','mx','fr','it','br','co','it','gr']}
            limitMaxLength={true}
            enableSearch={true}
            name="phone_number"
            value={contact.phone_number.value}
            onChange={phone_number => setContact({...contact, phone_number: phone_number})}
           
        />
       
      </FormGroup>
      <div>
        <FormGroup>
          <Label>Phone type</Label>
          <Input
            placeholder={!hasLabel ? 'landline or mobile' : ''}
            name="phone_type"
            required={true}
            value={contact.phone_type.value}
            onChange={handleChange}
            type='select'>

          <option name="mobile" value="mobile">Mobile</option>
          <option name="landline" value="landline">Landline</option>
          </Input>
        </FormGroup>
      </div>
      <div>
        <FormGroup>
        <Label>
          Choose Group/List</Label>
            <Select
              name="group"
              required={true}
              className="mb-3"
              closeMenuOnSelect={false}
              options={groups}
              getOptionLabel={({title}) => title}
              getOptionValue={({_id}) => _id}
              onChange={handleChange}.         <----ignore the period this is where the issue lies   
              isMulti
              placeholder="Add to a Group"
              isSearchable={true}
            />
        </FormGroup>
      </div>
     
      <div>
        <FormGroup>
          <Label>First Name</Label>
          <Input
            
            placeholder={!hasLabel ? 'First Name' : ''}
            name="firstName"
            value={contact.firstName.value}
            onChange={handleChange}
            type='input'
          />
        </FormGroup>
      </div>
      <div>
        <FormGroup>
          <Label>Last Name</Label>
          <Input
            placeholder={!hasLabel ? 'Last Name' : ''}
            name="lastName"
            value={contact.lastName.value}
            onChange={handleChange}
            type='input'
          />
        </FormGroup>
      </div>
      <div>
        <FormGroup>
          <Label>Company</Label>
          <Input
            placeholder={!hasLabel ? 'Company' : ''}
            name="company"
            value={contact.company.value}
            onChange={handleChange}
            type='input'
          />
        </FormGroup>
      </div>
      <div>
        <FormGroup>
          <Label>Email</Label>
          <Input
            placeholder={!hasLabel ? 'Email' : ''}
            name="email"
            value={contact.email.value}
            onChange={handleChange}
            type='email'
          />
        </FormGroup>
      </div>
  
      <Divider className="mt-4">or save without adding</Divider>   
      <FormGroup>
      <Button block color="primary" type="submit">Save</Button>
      </FormGroup>
    </Form>
  
  </>
 
    
  );
};

ContactForm.propTypes = {
  
  hasLabel: PropTypes.bool
};

ContactForm.defaultProps = {
  layout: 'basic',
  hasLabel: false
};

export default ContactForm;

标签: reactjs

解决方案


通过查看此处的文档https://github.com/JedWatson/react-select/tree/master/packages/react-select 我猜这是因为 react-selectonChange不会返回带有目标的事件,但是只返回所选内容的值。它的作用可能与 不同<Input>,因此您应该创建一个新函数。如果您所做的只是将所选值设置为 state,那么您可以使用箭头函数。

我认为这应该可以工作,或者类似的东西(我还没有测试过)

<Select 
    name="group" 
    required={true} 
    className="mb-3" 
    closeMenuOnSelect={false}
    options={groups}
    getOptionLabel={({title}) => title}
    getOptionValue={({_id}) => _id}
    onChange={(selectedGroup) => 
        {setContact({...contact, group: selectedGroup})}}         
    isMulti
    placeholder="Add to a Group"
    isSearchable={true}
/>

如果这不起作用,请使用您的原始功能,console.log(e)您可能可以从那里找出答案。


推荐阅读