【问题标题】:Object is possibly undefined react typescript in the dropdown component对象可能是下拉组件中未定义的反应打字稿
【发布时间】:2021-09-25 19:52:27
【问题描述】:

我正在创建一个下拉组件,但 typescript 在 options.map 和 selectedOption.title 案例中抛出了几个错误:

import React, { useRef,useState, useEffect } from "react";
import useToggle from '../hooks/useToggle';
import  useDetectOutsideClick  from '../hooks/useOutsideClick';

import "./select.scss";
interface TProduct {
    title?: string;
    options?: [];
    getDropDownValue?: any;
  }

  interface TOption {
    title?: string;
    value?: string;
    id?: any;
  }

const Select = (props: TProduct) => {
    let { title, options, getDropDownValue } = props;
    const dropdownRef = useRef(null);
    const [visibility, setVisibility] =  useDetectOutsideClick(dropdownRef, false);
      const [selectedOption, setSelectedOption] = useState<TOption>({});
  
      return (
          
              <div
          className="base-select"
          ref={dropdownRef}
                  onClick={e =>  {
                      setVisibility(!visibility);
                  
                  }}
              >
                  <div className="selected-option">
                      <span
                          title={
                              selectedOption === ""
                                  ? title
                                  : selectedOption.title
                          }
                      >
                          {selectedOption === ""
                              ? title
                              : selectedOption.title.length <= 20
                              ? selectedOption.title
                              : selectedOption && selectedOption.title  && `${selectedOption.title.slice(0, 20)}`}
                      </span>
                      
                  </div>
                  {visibility && (
                      <div className="options">
                          <ul>
                      
                              {options
                                  .map((option) => (
                                      <li
                                          key={index}
                                          className={
                                             selectedOption && selectedOption ===       option
                                                  ? "active-option"
                                                  : ''
                                          }
                                          onClick={() => {
                        setSelectedOption(option);
                        getDropDownValue(option);
                       
                      }
                                          }
                                      >
                                          {option.title}
                                      </li>
                                  ))}
                          </ul>
                      </div>
                  )}
              </div>
      );
     };

    export default Select

所以列表项和标题的循环都会抛出选项类型和 selectedOptions.title 类型的错误 Object is possible undefined

出了什么问题,如何解决?

【问题讨论】:

  • 添加? 以在访问属性之前检查对象的可用性。比如possiblyUndefinedObject?.title
  • 我还建议将&amp;&amp; 运算符更新为selectedOption?.id === option.id,您不可能使用=====selectedOption 等对象与另一个对象匹配。
  • @SultanH。它显示了 key= {index} 以及循环中 option.title 中的错误。我猜 ?标记并不能解决问题。如果可以,请您回答问题?

标签: javascript reactjs typescript react-hooks typescript2.0


【解决方案1】:

可以通过使用 TS 中的 ? 运算符安全地键入您的 optionselectedOption 并将 index 添加到您的 options.map 回调函数中来修复。

<div
    className="base-select"
    ref={dropdownRef}
    onClick={e =>  {
      setVisibility(!visibility);
    }}
  >
    <div className="selected-option">
      <span
        title={
          selectedOption === ""
            ? title
            : selectedOption?.title
        }
      >
        {selectedOption === ""
          ? title
          : selectedOption?.title?.length <= 20
            ? selectedOption?.title
            : selectedOption?.title && `${selectedOption?.title?.slice(0, 20)}`}
      </span>

    </div>
    {visibility && (
      <div className="options">
        <ul>
          {options
            .map((option, index) => (
              <li
                key={index}
                className={
                  selectedOption?.id === option?.id
                    ? "active-option"
                    : ""
                }
                onClick={() => {
                  setSelectedOption(option);
                  getDropDownValue(option);
                }}
              >
                {option?.title}
              </li>
            ))}
        </ul>
      </div>
    )}
  </div>

我强烈建议严格键入您正在创建的任何 react 组件的 props,TS 在这里最有用。

例如:

type CustomSelectProps = {
  options?: Array<TOption>;
  title?: string;
  getDropDownValue?: (option: TOption) => void;
}
const Select: React.FC<CustomSelectProps> = (props) => {
  // ...component content...
}

【讨论】:

  • 它仍然显示 {selectedOption === "" ?标题 : selectedOption?.title.length ${selectedOption?.title.slice(0, 20)}}
  • 已更新,@NewTechLover 只是在那里应用相同的概念.. 因为selectedOption 可能是undefined,在这种情况下标题本身就是,因此,我们会像undefined.slice 那样做某事这是不可能的。
猜你喜欢
  • 1970-01-01
  • 2021-11-27
  • 2019-07-30
  • 2019-09-15
  • 1970-01-01
  • 2022-01-26
  • 2021-02-12
  • 2021-12-01
  • 2021-08-24
相关资源
最近更新 更多