我的帖子部分为什么没有显示内容。我必须手动刷新它。

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

Why my post section is not showing Content. I have to manually Refresh it

问题

I am using switch for redirecting. In navbar there is All post link when user click on it it should load the all post but it is not reloading. I have to manually refresh the page to make it appear the content of all post.

In app.jsx section Navbar is imported along with routes which is routing to post and the component is <AllPost />. In Navbar I have made a <Link to="post"> but when I am clicking on all post it is showing but empty. When I refresh it it start showing me the content.

AllPost.jsx

import React, { useEffect, useState } from "react";
import { db, storage } from "../firebase-config";
import { collection, getDocs, addDoc } from "firebase/firestore";
import { ref, uploadBytesResumable, getDownloadURL } from "firebase/storage";
import Loading from "../components/Loading";
import { withAuthenticationRequired } from "@auth0/auth0-react";

function AllPost() {
  const [user, setUser] = useState([]);
  const [image, setImage] = useState("");

  const [data, setData] = useState({});

  const [name, setName] = useState("");
  const [description, setDescription] = useState("");
  const [estate, setEstate] = useState("");

  const [file, setFile] = useState();
  const userCollectionRef = collection(db, "posts");

  const handleButton = async () => {
    await addDoc(userCollectionRef, {
      name: name,
      description: description,
      estate: estate,
      image: image,
    });
  };

  useEffect(() => {
    const uploadFiles = () => {
      const fileName = new Date().getTime() + file.name;
      const storageRef = ref(storage, fileName);

      const uploadTask = uploadBytesResumable(storageRef, file);

      uploadTask.on(
        "state_changed",
        (snapshot) => {
          const progress =
            (snapshot.bytesTransferred / snapshot.totalBytes) * 100;
          console.log("Upload is " + progress + "% done");
          switch (snapshot.state) {
            case "paused":
              console.log("Upload is paused");
              break;
            case "running":
              console.log("Upload is running");
              break;
            default:
              break;
          }
        },
        (error) => {
          console.log(error);
        },
        () => {
          getDownloadURL(uploadTask.snapshot.ref).then((downloadURL) => {
            setImage(downloadURL);
          });
        }
      );
    };
    file && uploadFiles();
  }, [file]);

  useEffect(() => {
    const getUsers = async () => {
      const data = await getDocs(userCollectionRef);
      setUser(data.docs.map((doc) => ({ ...doc.data(), id: doc.id })));
    };
    getUsers();
  }, []);

  return (
    <div>
      <input
        type="file"
        onChange={(e) => {
          setFile(e.target.files[0]);
        }}
      />
      <input
        type="text"
        onChange={(e) => {
          setName(e.target.value);
        }}
        placeholder="estate"
      />
      <input
        type="text"
        onChange={(e) => {
          setDescription(e.target.value);
        }}
        placeholder="description"
      />
      <input
        type="text"
        onChange={(e) => {
          setEstate(e.target.value);
        }}
        placeholder="name"
      />
      <button onClick={handleButton}>Click me</button>

      <div className="square center-div">
        {user.map((item) => {
          return (
            <div>
              <div className="circle-pfp">{item.description}</div>
              <h3>{item.estate}</h3>
              <h1>{item.name}</h1>
              <img src={item.image} alt="" />
            </div>
          );
        })}
      </div>
    </div>
  );
}

export default AllPost;

Navbar.jsx

import React from "react";
import { withAuth0 } from "@auth0/auth0-react";
import { Component } from "react";
import "./NavbarStyles.css";
import { BrowserRouter as Router, Switch, Route, Link } from "react-router-dom";
import AllPost from "./AllPost";
import Dashboard from "./dashboard";

class Navbar extends Component {
  state = { clicked: false };
  handleClick = () => {
    this.setState({ clicked: !this.state.clicked });
  };
  render() {
    const { user, loginWithRedirect, logout, isAuthenticated } =
      this.props.auth0;
    return (
      <>
        <Router>
          <nav>
            <a href="index.html">
              <svg
                id="logo-16"
                width="109"
                height="43"
                viewBox="0 0 109 43"
                fill="none"
                xmlns="http://www.w3.org/2000/svg"
              >
                {/* ... (SVG content) ... */}
              </svg>
            </a>
            <div>
              <ul
                id="navbar"
                className={this.state.clicked ? "#navbar active" : "#navbar"}
              >
                <Link to="post">All Post</Link>
                {isAuthenticated && (
                  <li>
                    <p className="para">Welcome, {user.name}</p>
                  </li>
                )}

                {isAuthenticated ? (
                  <li>
                    <button
                      onClick={() =>
                        logout({
                          logoutParams: { returnTo: window.location.origin },
                        })
                      }
                    >
                      Log Out
                    </button>
                  </li>
                ) : (
                  <li>
                    <button onClick={() => loginWithRedirect()}>Log In</button>
                  </li>
                )}
              </ul>
            </div>
            <div id="mobile" onClick={this.handleClick}>
              <i
                id="bar"
                className={
                  this.state.clicked ? "fas fa-times" : "fas fa-bars"
                }
              ></i>
            </div>
          </nav>
        </Router>
      </>
    );
  }
}

export default withAuth0(Navbar);

App.jsx

import "./App.css";
import Navbar from "./components/Navbar";
import { Router, Route, Switch } from "react-router-dom";
import { Footer } from "./components/Footer";
import Dashboard from "./components/dashboard";
import { useAuth0 } from "@auth0/auth0-react";
import { createBrowserHistory } from "history";
import { HeroText } from "./components/hero";
import Loading from "./components/Loading";
import { Profile } from "./components/profile";
import AllPost from "./components/AllPost";
const history = createBrowserHistory();

function App() {
  const { isLoading, error, isAuthenticated } = useAuth0();

  if (error) {
    return <div>Oops... {error.message}</div>;
  }

  if (isLoading) {
    return <Loading />;
  }
  return (
    <Router history={history}>
      <Navbar />
      <Switch>
        <Route
          path="/"
          exact
          component={isAuthenticated ? Dashboard : HeroText}
        />
        <Route path="/post" component={AllPost} />
        <Route path="/profile" component={Profile} />
        <Route
          path="

<details>
<summary>英文:</summary>

I am using switch for redirecting. In navbar there is All post link when user click on it it should load the all post but it is not reloading. I have to manually refresh the page to make it appear the content of all post.

In app.jsx section `Navbar` is imported along with routes which is routing to post and the component is `&lt;AllPost /&gt;`. In `Navbar` I have made a `&lt;Link to=&quot;post&quot;&gt; ` but when I am clicking on all post it is showing but empty. When I refresh it it start showing me the content.

AllPost.jsx
```jsx
import React, { useEffect, useState } from &quot;react&quot;;
import { db, storage } from &quot;../firebase-config&quot;;
import { collection, getDocs, addDoc } from &quot;firebase/firestore&quot;;
import { ref, uploadBytesResumable, getDownloadURL } from &quot;firebase/storage&quot;;
import Loading from &quot;../components/Loading&quot;;
import { withAuthenticationRequired } from &quot;@auth0/auth0-react&quot;;

function AllPost() {
  const [user, setUser] = useState([]);
  const [image, setImage] = useState(&quot;&quot;);

  const [data, setData] = useState({});

  const [name, setName] = useState(&quot;&quot;);
  const [description, setDescription] = useState(&quot;&quot;);
  const [estate, setEstate] = useState(&quot;&quot;);

  const  = useState();
  const userCollectionRef = collection(db, &quot;posts&quot;);

  const handleButton = async () =&gt; {
    await addDoc(userCollectionRef, {
      name: name,
      description: description,
      estate: estate,
      image: image,
    });
  };

  useEffect(() =&gt; {
    const uploadFiles = () =&gt; {
      const fileName = new Date().getTime() + file.name;
      // console.log(fileName);
      const storageRef = ref(storage, fileName);

      const uploadTask = uploadBytesResumable(storageRef, file);

      // Register three observers:
      // 1. &#39;state_changed&#39; observer, called any time the state changes
      // 2. Error observer, called on failure
      // 3. Completion observer, called on successful completion
      uploadTask.on(
        &quot;state_changed&quot;,
        (snapshot) =&gt; {
          // Observe state change events such as progress, pause, and resume
          // Get task progress, including the number of bytes uploaded and the total number of bytes to be uploaded
          const progress =
            (snapshot.bytesTransferred / snapshot.totalBytes) * 100;
          console.log(&quot;Upload is &quot; + progress + &quot;% done&quot;);
          switch (snapshot.state) {
            case &quot;paused&quot;:
              console.log(&quot;Upload is paused&quot;);
              break;
            case &quot;running&quot;:
              console.log(&quot;Upload is running&quot;);
              break;
            default:
              break;
          }
        },
        (error) =&gt; {
          console.log(error);
        },
        () =&gt; {
          // Handle successful uploads on complete
          // For instance, get the download URL: https://firebasestorage.googleapis.com/...
          getDownloadURL(uploadTask.snapshot.ref).then((downloadURL) =&gt; {
            // console.log(&quot;File available at&quot;, downloadURL);
            setImage(downloadURL);
          });
        }
      );
    };
    file &amp;&amp; uploadFiles();
  }, );

  useEffect(() =&gt; {
    const getUsers = async () =&gt; {
      const data = await getDocs(userCollectionRef);
      setUser(data.docs.map((doc) =&gt; ({ ...doc.data(), id: doc.id })));
      // console.log(data);
    };
    getUsers();
  }, []);

  return (
    &lt;div&gt;
      &lt;input
        type=&quot;file&quot;
        onChange={(e) =&gt; {
          setFile(e.target.files[0]);
        }}
      /&gt;
      &lt;input
        type=&quot;text&quot;
        onChange={(e) =&gt; {
          setName(e.target.value);
        }}
        placeholder=&quot;estate&quot;
      /&gt;
      &lt;input
        type=&quot;text&quot;
        onChange={(e) =&gt; {
          setDescription(e.target.value);
        }}
        placeholder=&quot;description&quot;
      /&gt;
      &lt;input
        type=&quot;text&quot;
        onChange={(e) =&gt; {
          setEstate(e.target.value);
        }}
        placeholder=&quot;name&quot;
      /&gt;
      &lt;button onClick={handleButton}&gt;Click me&lt;/button&gt;

      &lt;div className=&quot;square center-div&quot;&gt;
        {user.map((item) =&gt; {
          return (
            &lt;div&gt;
              &lt;div className=&quot;circle-pfp&quot;&gt;{item.description}&lt;/div&gt;
              &lt;h3&gt;{item.estate}&lt;/h3&gt;
              &lt;h1&gt;{item.name}&lt;/h1&gt;
              &lt;img src={item.image} alt=&quot;&quot; /&gt;
            &lt;/div&gt;
          );
        })}
      &lt;/div&gt;
    &lt;/div&gt;
  );
}

// export default withAuthenticationRequired(AllPost, {
//   onRedirecting: () =&gt; &lt;Loading /&gt;,
// });
export default AllPost;

Navbar.jsx

import React from &quot;react&quot;;
import { withAuth0 } from &quot;@auth0/auth0-react&quot;;
import { Component } from &quot;react&quot;;
import &quot;./NavbarStyles.css&quot;;
import { BrowserRouter as Router, Switch, Route, Link } from &quot;react-router-dom&quot;;
import AllPost from &quot;./AllPost&quot;;
import Dashboard from &quot;./dashboard&quot;;

class Navbar extends Component {
  state = { clicked: false };
  handleClick = () =&gt; {
    this.setState({ clicked: !this.state.clicked });
  };
  render() {
    const { user, loginWithRedirect, logout, isAuthenticated } =
      this.props.auth0;
    return (
      &lt;&gt;
        &lt;Router&gt;
          &lt;nav&gt;
            &lt;a href=&quot;index.html&quot;&gt;
              &lt;svg
                id=&quot;logo-16&quot;
                width=&quot;109&quot;
                height=&quot;43&quot;
                viewBox=&quot;0 0 109 43&quot;
                fill=&quot;none&quot;
                xmlns=&quot;http://www.w3.org/2000/svg&quot;
              &gt;
                {&quot; &quot;}
                &lt;path
                  d=&quot;M64.9315 11.4284C62.1883 8.6852 58.9316 6.5091 55.3475 5.0245C51.7633 3.5399 47.9219 2.7758 44.0424 2.7758C40.1629 2.7758 36.3215 3.5399 32.7373 5.0245C29.1532 6.5091 25.8965 8.6852 23.1533 11.4284L44.0424 32.3174L64.9315 11.4284Z&quot;
                  class=&quot;ccompli1&quot;
                  fill=&quot;#FFD200&quot;
                &gt;&lt;/path&gt;{&quot; &quot;}
                &lt;path
                  d=&quot;M44.0686 32.3475C46.8118 35.0907 50.0684 37.2667 53.6526 38.7513C57.2367 40.2359 61.0782 41 64.9577 41C68.837 41 72.679 40.2359 76.263 38.7513C79.847 37.2667 83.104 35.0907 85.847 32.3475L64.9577 11.4584L44.0686 32.3475Z&quot;
                  class=&quot;ccompli2&quot;
                  fill=&quot;#06E07F&quot;
                &gt;&lt;/path&gt;{&quot; &quot;}
                &lt;path
                  d=&quot;M44.017 32.3429C41.2738 35.0861 38.0171 37.2621 34.433 38.7467C30.8488 40.2313 27.0074 40.9954 23.1279 40.9954C19.2484 40.9954 15.407 40.2313 11.8228 38.7467C8.2387 37.2621 4.982 35.0861 2.2388 32.3429L23.1279 11.4538L44.017 32.3429Z&quot;
                  class=&quot;ccustom&quot;
                  fill=&quot;#E3073C&quot;
                &gt;&lt;/path&gt;{&quot; &quot;}
                &lt;path
                  d=&quot;M64.9831 11.433C67.726 8.6898 70.983 6.5138 74.567 5.0292C78.151 3.5446 81.993 2.7805 85.872 2.7805C89.752 2.7805 93.593 3.5446 97.177 5.0292C100.761 6.5138 104.018 8.6898 106.761 11.433L85.872 32.3221L64.9831 11.433Z&quot;
                  class=&quot;ccustom&quot;
                  fill=&quot;#1F84EF&quot;
                &gt;&lt;/path&gt;{&quot; &quot;}
              &lt;/svg&gt;
            &lt;/a&gt;
            &lt;div&gt;
              &lt;ul
                id=&quot;navbar&quot;
                className={this.state.clicked ? &quot;#navbar active&quot; : &quot;#navbar&quot;}
              &gt;
                &lt;Link to=&quot;post&quot;&gt;All Post&lt;/Link&gt;
                {isAuthenticated &amp;&amp; (
                  &lt;li&gt;
                    &lt;p className=&quot;para&quot;&gt;Welcome , {user.name}&lt;/p&gt;
                  &lt;/li&gt;
                )}

                {isAuthenticated ? (
                  &lt;li&gt;
                    &lt;button
                      onClick={() =&gt;
                        logout({
                          logoutParams: { returnTo: window.location.origin },
                        })
                      }
                    &gt;
                      Log Out
                    &lt;/button&gt;
                  &lt;/li&gt;
                ) : (
                  &lt;li&gt;
                    &lt;button onClick={() =&gt; loginWithRedirect()}&gt;Log In&lt;/button&gt;
                  &lt;/li&gt;
                )}
              &lt;/ul&gt;
            &lt;/div&gt;
            &lt;div id=&quot;mobile&quot; onClick={this.handleClick}&gt;
              &lt;i
                id=&quot;bar&quot;
                className={this.state.clicked ? &quot;fas fa-times&quot; : &quot;fas fa-bars&quot;}
              &gt;&lt;/i&gt;
            &lt;/div&gt;
          &lt;/nav&gt;
        &lt;/Router&gt;
      &lt;/&gt;
    );
  }
}

export default withAuth0(Navbar);

App.jsx

import &quot;./App.css&quot;;
import Navbar from &quot;./components/Navbar&quot;;
import { Router, Route, Switch } from &quot;react-router-dom&quot;;

import { Footer } from &quot;./components/Footer&quot;;
import Dashboard from &quot;./components/dashboard&quot;;
import { useAuth0 } from &quot;@auth0/auth0-react&quot;;
import { createBrowserHistory } from &quot;history&quot;;
import { HeroText } from &quot;./components/hero&quot;;
import Loading from &quot;./components/Loading&quot;;
import { Profile } from &quot;./components/profile&quot;;
import AllPost from &quot;./components/AllPost&quot;;
const history = createBrowserHistory();

function App() {
  const { isLoading, error, isAuthenticated } = useAuth0();

  if (error) {
    return &lt;div&gt;Oops... {error.message}&lt;/div&gt;;
  }

  if (isLoading) {
    return &lt;Loading /&gt;;
  }
  return (
    &lt;Router history={history}&gt;
      &lt;Navbar /&gt;
      &lt;Switch&gt;
        &lt;Route
          path=&quot;/&quot;
          exact
          component={isAuthenticated ? Dashboard : HeroText}
        /&gt;
        &lt;Route path=&quot;/post&quot; component={AllPost} /&gt;
        &lt;Route path=&quot;/profile&quot; component={Profile} /&gt;
        &lt;Route
          path=&quot;*&quot;
          component={() =&gt; {
            return &lt;div&gt;404 , PAGE NOT FOUND&lt;/div&gt;;
          }}
        /&gt;
      &lt;/Switch&gt;
      &lt;Footer /&gt;
    &lt;/Router&gt;
  );
}

export default App;

答案1

得分: 0

问题

该应用程序正在渲染多个路由组件,一个在 App 中,另一个在 Navbar 中。当单击 Navbar 中的链接时,Navbar 渲染的 BrowserRouter 处理导航操作,即更新 URL 到目标路径。由 App 渲染的 Router 永远不会意识到这个在 React 树下处理的导航操作。换句话说,每个路由器都独立运行,并且在导航操作上不共享任何上下文或信息。App 中的外部路由器在页面重新加载之前不会“看到”新路径,并且 所有 路由器都会重新挂载并检查 URL 路径以确定应该匹配和渲染什么。

解决方案

您只需要一个路由器为整个应用程序提供路由上下文,因此请删除其中一个。我建议删除 Navbar 渲染的多余路由器,以便它接收并访问由 App 渲染的 Router 提供的路由上下文。

示例:

class Navbar extends Component {
  state = { clicked: false };

  handleClick = () => {
    this.setState(prevState => ({
      clicked: !prevState.clicked
    }));
  };

  render() {
    const {
      user,
      loginWithRedirect,
      logout,
      isAuthenticated
    } = this.props.auth0;

    return (
      <nav>
        <a href="index.html">
          <svg
            id="logo-16"
            width="109"
            height="43"
            viewBox="0 0 109 43"
            fill="none"
            xmlns="http://www.w3.org/2000/svg"
          >
            {/* ... */}
          </svg>
        </a>
        <div>
          <ul
            id="navbar"
            className={this.state.clicked ? "#navbar active" : "#navbar"}
          >
            <Link to="post">All Post</Link>
            {isAuthenticated && (
              <li>
                <p className="para">Welcome , {user.name}</p>
              </li>
            )}

            {isAuthenticated ? (
              <li>
                <button
                  onClick={() =>
                    logout({
                      logoutParams: { returnTo: window.location.origin },
                    })
                  }
                >
                  Log Out
                </button>
              </li>
            ) : (
              <li>
                <button onClick={() => loginWithRedirect()}>Log In</button>
              </li>
            )}
          </ul>
        </div>
        <div id="mobile" onClick={this.handleClick}>
          <i
            id="bar"
            className={this.state.clicked ? "fas fa-times" : "fas fa-bars"}
          ></i>
        </div>
      </nav>
    );
  }
}

export default withAuth0(Navbar);
function App() {
  const { isLoading, error, isAuthenticated } = useAuth0();

  if (error) {
    return <div>Oops... {error.message}</div>;
  }

  if (isLoading) {
    return <Loading />;
  }

  return (
    <Router history={history}> // <-- 提供路由上下文
      <Navbar />               // <-- 访问路由上下文
      <Switch>
        <Route
          path="/"
          exact
          component={isAuthenticated ? Dashboard : HeroText}
        />
        <Route path="/post" component={AllPost} />
        <Route path="/profile" component={Profile} />
        <Route
          path="*"
          render={() => {
            return <div>404 , PAGE NOT FOUND</div>;
          }}
        />
      </Switch>
      <Footer />
    </Router>
  );
}

Note: I have translated the provided code, as per your request, without additional content.

英文:

Issue

The app is rendering more than one router component, one in App and another in Navbar. When a link in Navbar is clicked the BrowserRouter that Navbar renders handles the navigation action, i.e. it updates the URL to the target path. The Router rendered by App is never aware of this handled navigation action lower down the ReactTree. In other words, each router functions and operates independently and don't share any context or information elsewhere for the navigation actions they effect/handle. The outer Router in App doesn't "see" the new path until the page is reloaded and all routers mount again and check the URL path to see what they should match and render.

Solution

You need only one router to provide a routing context to the entire app, so remove one of them. I suggest removing the extraneous router that Navbar is rendering so it receives and accesses the routing context provided by the Router that App renders.

Example:

class Navbar extends Component {
  state = { clicked: false };

  handleClick = () =&gt; {
    this.setState(prevState =&gt; ({
      clicked: !prevState.clicked
    }));
  };

  render() {
    const {
      user,
      loginWithRedirect,
      logout,
      isAuthenticated
    } = this.props.auth0;

    return (
      &lt;nav&gt;
        &lt;a href=&quot;index.html&quot;&gt;
          &lt;svg
            id=&quot;logo-16&quot;
            width=&quot;109&quot;
            height=&quot;43&quot;
            viewBox=&quot;0 0 109 43&quot;
            fill=&quot;none&quot;
            xmlns=&quot;http://www.w3.org/2000/svg&quot;
          &gt;
            ...
          &lt;/svg&gt;
        &lt;/a&gt;
        &lt;div&gt;
          &lt;ul
            id=&quot;navbar&quot;
            className={this.state.clicked ? &quot;#navbar active&quot; : &quot;#navbar&quot;}
          &gt;
            &lt;Link to=&quot;post&quot;&gt;All Post&lt;/Link&gt;
            {isAuthenticated &amp;&amp; (
              &lt;li&gt;
                &lt;p className=&quot;para&quot;&gt;Welcome , {user.name}&lt;/p&gt;
              &lt;/li&gt;
            )}

            {isAuthenticated ? (
              &lt;li&gt;
                &lt;button
                  onClick={() =&gt;
                    logout({
                      logoutParams: { returnTo: window.location.origin },
                    })
                  }
                &gt;
                  Log Out
                &lt;/button&gt;
              &lt;/li&gt;
            ) : (
              &lt;li&gt;
                &lt;button onClick={() =&gt; loginWithRedirect()}&gt;Log In&lt;/button&gt;
              &lt;/li&gt;
            )}
          &lt;/ul&gt;
        &lt;/div&gt;
        &lt;div id=&quot;mobile&quot; onClick={this.handleClick}&gt;
          &lt;i
            id=&quot;bar&quot;
            className={this.state.clicked ? &quot;fas fa-times&quot; : &quot;fas fa-bars&quot;}
          &gt;&lt;/i&gt;
        &lt;/div&gt;
      &lt;/nav&gt;
    );
  }
}

export default withAuth0(Navbar);
function App() {
  const { isLoading, error, isAuthenticated } = useAuth0();

  if (error) {
    return &lt;div&gt;Oops... {error.message}&lt;/div&gt;;
  }

  if (isLoading) {
    return &lt;Loading /&gt;;
  }

  return (
    &lt;Router history={history}&gt; // &lt;-- Provides routing context
      &lt;Navbar /&gt;               // &lt;-- Accesses routing context
      &lt;Switch&gt;
        &lt;Route
          path=&quot;/&quot;
          exact
          component={isAuthenticated ? Dashboard : HeroText}
        /&gt;
        &lt;Route path=&quot;/post&quot; component={AllPost} /&gt;
        &lt;Route path=&quot;/profile&quot; component={Profile} /&gt;
        &lt;Route
          path=&quot;*&quot;
          render={() =&gt; {
            return &lt;div&gt;404 , PAGE NOT FOUND&lt;/div&gt;;
          }}
        /&gt;
      &lt;/Switch&gt;
      &lt;Footer /&gt;
    &lt;/Router&gt;
  );
}

huangapple
  • 本文由 发表于 2023年6月29日 17:02:27
  • 转载请务必保留本文链接:https://go.coder-hub.com/76579590.html
匿名

发表评论

匿名网友

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

确定