簡體   English   中英

反應如何在沒有渲染組件的情況下通過 state

[英]React how to pass state without rendering component

我有一個問題,當我從根目錄開始並單擊鏈接時,所有狀態都加載正常,但是當我將 URL 復制並粘貼到新的 window 中時它沒有顯示,我假設它是正確的,因為之前組件沒有被渲染來設置 state?

希望有人可以向我指出一些有用的文章,或者甚至以前經歷過這種情況?

這是我為更好地展示我的意思而制作的屏幕錄像的鏈接https://youtu.be/M0390D4oJDg

代碼

import React from "react";
import { useLocation, useParams } from "react-router";
import PostBlock from "./PostBlock";




const PostList = () => {
  const {thread} = useParams()
  const { state: { description, title } = {} } = useLocation();

  return (
    <div>
      <div className="m-10 flex justify-center">
        <div style={{ width: "1216px" }}>
          <div className="flex justify-center">
            <div className="flex-1 justify-center mb-5 p-5 h-64 border border-gray-300">
              <div>{title}</div>
              <div>{description}</div>
            </div>
          </div>
          <table className="min-w-full table-auto">
            <thead className="justify-between">
              <tr className="bg-gray-800">
                <th className="px-8 py-2 text-left text-white">Posts</th>
              </tr>
            </thead>
            <tbody className="bg-gray-200">
              <PostBlock thread={thread}/>
            </tbody>
          </table>
        </div>
      </div>
    </div>
  );
};

export default PostList;

關聯

 <Link to={{ pathname: `/thread/${thread}`, state: {title: title, description: description} }}>

URL

http://localhost:3000/thread/jxvgOKPrSiCnI2ocDxgJ

這個反應的東西比我最初想象的要難

不要輕易放棄。 這是美好的事物之一!


從可選鏈接開始。

const title = useLocation()?.state?.title;
const description = useLocation()?.state?.description;

如果不支持,請使用&&

const title = useLocation() && useLocation().state && useLocation().state.title;
const description = useLocation() && useLocation().state && useLocation().state.description;

只有當titledescription不是null時,才呈現您的內容。

const PostList = () => {
  const { thread } = useParams();
  const title = useLocation() && useLocation().state && useLocation().state.title;
  const description = useLocation() && useLocation().state && useLocation().state.description;

  return title && description ? <div></div> : null;
};

現在代碼不會呈現內容,除非這兩個值都被設置。 這將確保您的代碼加載沒有任何錯誤。

我對您的問題到底是什么感到有些困惑,但是您的代碼存在一些問題。 嘗試這個:

const PostList = () => {
  const { thread } = useParams();
  const { state: { description, title } = {} } = useLocation();

  return <div></div>;
};

沒有理由初始化useLocation()兩次。 您也可以將其初始化為一個常量,然后通過它訪問描述和 state。

const PostList = () => {
  const { thread } = useParams();
  const location = useLocation();

  console.log(location.state.title, location.state.description);

  return <div></div>;
};

此外,如果您的 state 為空,您可以合並object?.property方法作為故障保護:

console.log(location?.state?.title);

此處查看正確的useLocation用法

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM