“React中读取子字符串时出现未定义错误”

huangapple go评论74阅读模式
英文:

Undefined error when reading substring in React

问题

I'm getting this error on my React web application: TypeError: Cannot read properties of undefined (reading 'substring').

const DocumentationDetail = () => {
    const router = useRouter();
    const { user } = useAuth();
    const id = router.asPath.substring(1);
    const { data } = useDocumentationGet(parseInt(id));

    return (
        <>
            <Head>
                <title>{data.title}</title>
            </Head>
            <main>
                <MainLayout>
                    <div className={styles.container}>
                        <h1 className={styles.title}>{data.title}</h1>
                        <span className={styles.info}>Publicado {data.created_at.substring(8, 10)}/{data.created_at.substring(5, 7)}/{data.created_at.substring(0, 4)} por {data.author.name}</span>
                        <p className={styles.content}>{data.content}</p>
                    </div>
                </MainLayout>
            </main>
        </>
    );
}
export function useDocumentationGet(id) {
    const [data, setData] = useState([]);

    useEffect(() => {
        getDocumentationRequest(id)
            .then(res => {
                setData(res.data);
            })
    }, [])

    return { data };
}
export async function getDocumentationRequest(id) {
  try {
    const response = await fetch(
      `${process.env.NEXT_PUBLIC_API_URL}/documentation/${id}`,
      {
        method: 'GET',
        headers: {
          'Content-Type': 'application/json',
        },
      },
    );

    if (response.ok) {
      return { data: await response.json() };
    }

    return {
      status: false,
    };
  } catch (err) {
    return {
      status: false,
    };
  }
}

If I comment the span tag, everything works fine, I don't get it why I only get this undefined error in this line. I also tried using: data ? data.created_at.substring(8,10) : "".... but I got blank spaces on the span line.

英文:

I'm getting this error on my React web application: TypeError: Cannot read properties of undefined (reading 'substring').

const DocumentationDetail = () =&gt; {
    const router = useRouter();
    const { user } = useAuth();
    const id = router.asPath.substring(1);
    const { data } = useDocumentationGet(parseInt(id));

    return (
        &lt;&gt;
            &lt;Head&gt;
                &lt;title&gt;{ data.title }&lt;/title&gt;
            &lt;/Head&gt;
            &lt;main&gt;
                &lt;MainLayout&gt;
                    &lt;div className={styles.container}&gt;
                        &lt;h1 className={styles.title}&gt;{ data.title }&lt;/h1&gt;
                        &lt;span className={styles.info}&gt;Publicado { data.created_at.substring(8, 10) }/{ data.created_at.substring(5, 7) }/{ data.created_at.substring(0, 4) } por { data.author.name }&lt;/span&gt;
                        &lt;p className={styles.content}&gt;{ data.content }&lt;/p&gt;
                    &lt;/div&gt;

                &lt;/MainLayout&gt;
            &lt;/main&gt;
        &lt;/&gt;
    );
}
export function useDocumentationGet(id) {
    const [data, setData] = useState([]);

    useEffect(() =&gt; {
        getDocumentationRequest(id)
            .then(res =&gt; {
                setData(res.data);
            })
    }, [])

    return { data };
}
export async function getDocumentationRequest(id) {
  try {
    const response = await fetch(
      `${process.env.NEXT_PUBLIC_API_URL}/documentation/${id}`,
      {
        method: &#39;GET&#39;,
        headers: {
          &#39;Content-Type&#39;: &#39;application/json&#39;,
        },
      },
    );

    if (response.ok) {
      return { data: await response.json() };
    }

    return {
      status: false,
    };
  } catch (err) {
    return {
      status: false,
    };
  }
}

If I comment the span tag, everything works fine, I don't get it why I only get this undefined error in this line. I also tried using: data ? data.created_at.substring(8,10) : "".... but I got blank spaces on the span line.

答案1

得分: 0

Your data is being fetched after the component is rendered.

> i.e. data.created_at is empty at the time of render. There are many
> ways to fix this.

One of the way is to use Conditional Rendering using short circuit, i.e Rendering the component only once Data is ready to be used.
This way the component will render only when data is fetched.
Instead of just rendering the span tag, add a condition as mentioned below.

{
在组件渲染之后获取数据。

> 即 data.created_at 在渲染时为空。有许多
> 修复此问题的方法。

其中一种方法是使用短路条件渲染,即仅在数据准备好使用时渲染组件。
这样,组件将仅在数据获取时进行渲染。
而不仅仅渲染 span 标签,根据以下条件添加条件。

     {
	     data?.created_at &amp;&amp; data?.author?.name &amp;&amp;
	         &lt;span className={styles.info}&gt;
				 Publicado { data.created_at.substring(8, 10) }/{ data.created_at.substring(5, 7) }/{ data.created_at.substring(0, 4) } por { data.author.name }
			 &lt;/span&gt;
	 }
英文:

Your data is being fetched after the component is rendered.

> i.e. data.created_at is empty at the time of render. There are many
> ways to fix this.

One of the way is to use Conditional Rendering using short circuit, i.e Rendering the component only once Data is ready to be used.
This way the component will render only when data is fetched.
Instead of just rendering the span tag, add a condition as mentioned below.

     {
	     data?.created_at &amp;&amp; data?.author?.name &amp;&amp;
	         &lt;span className={styles.info}&gt;
				 Publicado { data.created_at.substring(8, 10) }/{ data.created_at.substring(5, 7) }/{ data.created_at.substring(0, 4) } por { data.author.name }
			 &lt;/span&gt;
	 }

huangapple
  • 本文由 发表于 2023年6月5日 05:58:55
  • 转载请务必保留本文链接:https://go.coder-hub.com/76402563.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定