简体   繁体   English

Object 可能是 null 反应/打字稿

[英]Object is possibly null react/typescript

I keep running in to this error, the code works fine in plain react but in typescript it keeps throwing this error "Object is possibly null".我一直遇到这个错误,代码在普通反应中工作正常,但在 typescript 中它一直抛出这个错误“对象可能为空”。 I tried countering it using "."我试着用“。”来反驳它。 but it didn't help.但它没有帮助。

second error in the log says "cannot read properties of null reading (textContent) "日志中的第二个错误是“无法读取 null 读取的属性(textContent)

I set this to false我将其设置为 false

"strictNullChecks": false,

Here is a sandbox - https://codesandbox.io/s/sweet-mclean-nrhcdq?file=/src/App.tsx这是一个沙箱 - https://codesandbox.io/s/sweet-mclean-nrhcdq?file=/src/App.tsx

This is the fetch api call -这是获取 api 调用 -

const [isLoading, setLoading] = useState(false);
  //storing data
  const [data, setData] = useState(false);

  //fetching data
  useEffect(() => {
    setLoading(true);

    const fetchList = async (): Promise<UsersList> => {
      const result: any = await fetch("https://randomuser.me/api/?results=20")
        .then((res) => res.json())
        .then((data) => {
          setData(data);
          setLoading(false);
          console.log(data);
          
        });
        
      return result;
    };
    fetchList();
    
    
  }, []);

This is the code that is causing me the problem, is there a better way of doing this?这是导致我出现问题的代码,有更好的方法吗? someone mentioned useref but im not sure how to implement it with a fetch call in useEffect.有人提到了 useref,但我不确定如何使用 useEffect 中的获取调用来实现它。

The desired output is for any text that includes Miss to have a blue background.所需的 output 是包含 Miss 的任何文本都具有蓝色背景。

const h2 = window.document.getElementById("person")!
  h2.innerHTML = h2.textContent!.replace(/[Miss]/g, "<span class='title'>Miss</span>");

.title {
background-color: blue;
}

Later in the html I have filtered and mapped through the data -后来在 html 中,我过滤并映射了数据 -

<div style={hoverStyle} className="grid grid-cols-4 gap-2 p-2 mt-20">
        {data?.results.filter((val: any)=>{
          if (searchUser === "") {
            return val
          } else if (val.name.first.toLowerCase().includes(searchUser.toLowerCase())) { 
              return val          
          } else if (val.email.toLowerCase().includes(searchUser.toLowerCase())){
            return val
          } else if 
            (val.location.city.toLowerCase().includes(searchUser.toLowerCase())){
              return val
            } 
        }).map((d: any) => (
              
          <div style={hoverStyle} className=" ease-in-out delay-150 hover:-translate-y-1 hover:scale-110 duration-300  border-white shadow-slate-500 bg-white hover:opacity-95 rounded-lg container p-5">
            <img className="rounded-full w-44 h-44 " src={d.picture.large} />
            <h2 id="person" >{d.name.title}</h2>

Any ideas?有任何想法吗?

You are mapping through an array so it creates multiple h2 elements that is why need to select all h2 elements, also do that when data loading finished.您正在通过一个数组进行映射,因此它会创建多个 h2 元素,这就是为什么需要 select 所有 h2 元素,并在数据加载完成时执行此操作。 try these changed lines.尝试这些更改的行。

 let h2 = document.querySelectorAll("h2")
  h2.innerHTML = !isLoading && h2.textContent?.replace(/[Miss]/g, "<span class='title'>Miss</span>");

Also here is the screen shot taken from your sandbox attached after doing that.这也是在执行此操作后从您的沙箱中截取的屏幕截图。 Hope you are looking for the same.希望你正在寻找相同的。 在此处输入图像描述

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM