繁体   English   中英

React.js 数据只有在刷新后才第一次加载它工作

[英]React.js data won't load at the first time only after refresh it works

目前,我在 react.js 中建立了一个网站并且出现了一个问题。 我认为当我点击需要脚本的页面时,我第一次输入脚本不起作用。 但是在我刷新页面之后。 突然出现数据。 我认为我的 JavaScript 没有加载它,但是如果我刷新页面并开始工作

import React from 'react';
import "./Information.css";


function Information({imgStart,img, alt, name, age, gender,bio,qualification_acedemic,institution_acedemic,organisation,role,year,level,role_admin,level_admin,start_admin,end_admin
,area_expertise,book_pub,chp_book_pub,title_Areas,role_Areas,title_consult,role_consult,organisation_consult,fromTo_consult
,award,institution_award,year_award,activity_contribute,fromTo_contribute,role_contribute,name_degree,name_candidates,title_thesis,academic_level,academic_teach,course_teach,hourContact_teach,number_student_teach}) {

   
    return (
     
        <>
        <div className="container_details">
            <div className="row_details"
                style={{display: "flex", flexDirection: imgStart === 'start' ? "row-reverse" : "row" }}> 
                <div className="col-personal-logo"> 
                    <img src={img} alt={alt} className="personal-image"/>
                    <h2>{name}</h2>
                    <p>Age:{age}</p>
                    <p>Gender:{gender}</p>
                    <p></p>
                </div>  
                <div className="col-personal">
                    <button class="accordion">Biography</button>
                    <div class="panel">
                    
                    <p>{bio}</p>
                    </div>

                    <button class="accordion">Academic Qualification</button>
                    <div class="panel">
                    <p>Qualification: {qualification_acedemic}</p>
                    <p>Institution: {institution_acedemic}</p>
                    </div>

                    <button class="accordion">Professional</button>
                    <div class="panel">
                    <p>Organisation: {organisation}</p>
                    <p>Role: {role}</p>
                    <p>Year: {year}</p>
                    <p>Level: {level}</p>
                    </div>

                    
                </div>
                

            </div>

        </div>
     
            
        </>

        
    )
}

    


export default Information

索引.html

<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="utf-8" />
    <link rel="icon" href="%PUBLIC_URL%/favicon.ico" />
    <meta name="viewport" content="width=device-width, initial-scale=1" />
    <meta name="theme-color" content="#000000" />
    <meta
      name="description"
      content="Web site created using create-react-app"
    />
    <link rel="apple-touch-icon" href="%PUBLIC_URL%/logo192.png" />
    <link rel="stylesheet" href="https://use.fontawesome.com/releases/v5.15.0/css/all.css"
     integrity="sha384-OLYO0LymqQ+uHXELyx93kblK5YIS3B2ZfLGBmsJaUyor7CpMTBsahDHByqSuWW+q" crossorigin="anonymous">
   
    <link rel="manifest" href="%PUBLIC_URL%/manifest.json" />
  
    <title>UOW Portal</title>
  </head>
  <body>
    <noscript>You need to enable JavaScript to run this app.</noscript>
    <div id="root"></div>
   
    
  </body>
  <script>
    var acc = document.getElementsByClassName("accordion");
    var i;

    
        for (i = 0; i < acc.length; i++) {
        acc[i].addEventListener("click", function() {
            /* Toggle between adding and removing the "active" class,
            to highlight the button that controls the panel */
            this.classList.toggle("active");

            /* Toggle between hiding and showing the active panel */
            var panel = this.nextElementSibling;
            if (panel.style.display === "block") {
            panel.style.display = "none";
            } else {
            panel.style.display = "block";
            }
        });
        }

  </script>
</html>

应用程序.js

import React from 'react';
import "./App.css"
import Navbar from './components/Navbar';
import { Switch, Route} from 'react-router';
import { BrowserRouter } from 'react-router-dom'
import Home from './components/pages/HomePage/Home'
import Footer from './components/pages/Footer/Footer';
import Service from './components/Service';

import Info from './components/pages/Info/Info';
import infoMs from './components/pages/Info/infoMs';



function App(){
  return(
    <BrowserRouter>
      <Navbar />
      <Switch>
        <Route path='/' exact component={Home}/>
        <Route path='/service' exact component={Service}/>
        <Route path='/phua' component={Info}/>
        <Route path='/foong' component={infoMs}/>

      </Switch>
      
      <Footer />
    </BrowserRouter>
  );
}

 

export default App;

我认为这不是 React 的工作方式!

原因

or shouldn't work. React 使用所谓的客户端渲染,因此使用获取元素之类的事情不应该起作用。 scripts already running, so that it cannot find the elements. 因为,(CMIIW)当您的脚本已经运行时,元素的呈现还没有完成,因此它找不到元素。

解决方案

但是,如果您想让您的视图响应单击事件,您可以将您的功能放在组件上。 意思是,而不是使用 addEventListener 创建事件侦听器,您应该执行以下操作:
function Information(....) {
  ......

  <Accordion>
    <div>
      <p>Qualification: {qualification_acedemic}</p>
      <p>Institution: {institution_acedemic}</p>
    </div>
  </Accordion>

  ......
} 

不仅如此,您还应该使用 React 状态(基于钩子或基于组件的状态)创建打开/关闭状态。 并且您的点击处理程序应该切换状态 true 或 false。

然而,由于单词难以消化🥴,让我展示一个代码示例😄。 创建一个新组件 Accordion,如下所示:

 function Accordion({ children, title }) { const [show, setShow] = useState(false) const toggle = () => setShow(state => !state) return ( <div> <button class="accordion" onClick={toggle}>{title}</button> {show && <div class="panel"> {children} </div> } </div> ) }

然后像这样使用它:

 function Information(....) { ...... <Accordion> <div> <p>Qualification: {qualification_acedemic}</p> <p>Institution: {institution_acedemic}</p> </div> </Accordion> ...... }

这个手风琴组件应该能够独立打开和关闭。 如果你想让它依赖于另一个,你可以实现更高级的状态或使用第三方组件,也许是这个组件

结论

我认为你应该使用 React 的方式来让你的 UI 具有响应性,而不是尝试像使用 React 一样的普通方式。

暂无
暂无

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

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