<kbd id="afajh"><form id="afajh"></form></kbd>
<strong id="afajh"><dl id="afajh"></dl></strong>
    <del id="afajh"><form id="afajh"></form></del>
        1. <th id="afajh"><progress id="afajh"></progress></th>
          <b id="afajh"><abbr id="afajh"></abbr></b>
          <th id="afajh"><progress id="afajh"></progress></th>

          21 個(gè)整理 React 項(xiàng)目的最佳實(shí)踐

          共 10165字,需瀏覽 21分鐘

           ·

          2024-06-21 09:10

          今天,我們將討論一些改善React應(yīng)用程序運(yùn)行狀況的最佳實(shí)踐。

          這些規(guī)則應(yīng)用廣泛。因此,擁有這些知識勢在必行。

          unsetunset1. 使用JSX速記unsetunset

          嘗試使用JSX速記來傳遞布爾變量。

          舉個(gè)例子,假設(shè)你想要控制導(dǎo)Navbar組件的標(biāo)題可見性。

          return (
            <Navbar showTitle={true} />
          );

          return(
            <Navbar showTitle />  
          )

          unsetunset2. 使用三元運(yùn)算符unsetunset

          假設(shè)你想要根據(jù)role顯示用戶的詳細(xì)信息。

          const { role } = user;

          if(role === ADMIN) {
            return <AdminUser />
          }else{
            return <NormalUser />

          const { role } = user;

          return role === ADMIN ? <AdminUser /> : <NormalUser />

          unsetunset3. 利用對象字面量unsetunset

          對象字面量可以使代碼更具可讀性。

          假設(shè)你想要根據(jù)role顯示三種類型的用戶。因?yàn)檫x項(xiàng)的數(shù)量超過兩個(gè),所以不能使用三元。

          const {role} = user

          switch(role){
            case ADMIN:
              return <AdminUser />
            case EMPLOYEE:
              return <EmployeeUser />
            case USER:
              return <NormalUser />
          }

          const {role} = user

          const components = {
            ADMIN: AdminUser,
            EMPLOYEE: EmployeeUser,
            USER: NormalUser
          };

          const Component = components[role];

          return <Componenent />;

          現(xiàn)在看上去是不是好多了?!

          unsetunset4. 使用Fragmentunsetunset

          始終使用Fragment而不是Div。

          Fragment可幫助保持代碼干凈,且有利于性能,因?yàn)樵谔摂MDOM中少創(chuàng)建了一個(gè)節(jié)點(diǎn)。

          return (
            <div>
               <Component1 />
               <Component2 />
               <Component3 />
            </div>
            
          )

          return (
            <>
               <Component1 />
               <Component2 />
               <Component3 />
            </>
            
          )

          unsetunset5. 不要在渲染中定義函數(shù)unsetunset

          不要在渲染中定義函數(shù)。盡量將渲染內(nèi)部的邏輯保持在最小。

          return (
              <button onClick={() => dispatch(ACTION_TO_SEND_DATA)}>    // NOTICE HERE
                This is a bad example 
              </button>
            
          )

          const submitData = () => dispatch(ACTION_TO_SEND_DATA)

          return (
            <button onClick={submitData}>  
              This is a good example 
            </button>
            
          )

          unsetunset6. 使用Memounsetunset

          React.PureComponentMemo可以顯著提高應(yīng)用程序的性能,幫助我們避免不必要的渲染。

          import React, { useState } from "react";

          export const TestMemo = () => {
            const [userName, setUserName] = useState("faisal");
            const [count, setCount] = useState(0);

            const increment = () => setCount((count) => count + 1);

            return (
              <>
                <ChildrenComponent userName={userName} />
                <button onClick={increment}> Increment </button>
              </>

            );
          };

          const ChildrenComponent =({ userName }) => {
            console.log("rendered", userName);
            return <div> {userName} </div>;
          };

          盡管子組件應(yīng)該只呈現(xiàn)一次,因?yàn)?code style="color: rgb(155, 110, 35);font-size: 14px;line-height: 1.8em;letter-spacing: 0em;background: none 0% 0% / auto no-repeat scroll padding-box border-box rgb(255, 245, 227);width: auto;height: auto;margin-left: 2px;margin-right: 2px;padding: 2px 4px;border-style: none;border-width: 3px;border-color: rgb(0, 0, 0) rgba(0, 0, 0, 0.4) rgba(0, 0, 0, 0.4);border-radius: 4px;font-family: Operator Mono, Consolas, Monaco, Menlo, monospace;word-break: break-all;">count的值與ChildComponent無關(guān)。

          但是,每次單擊按鈕時(shí),它都會呈現(xiàn)。

          讓我們將ChildComponent編輯為:

          import React ,{useState} from "react";

          const ChildrenComponent = React.memo(({userName}) => {
              console.log('rendered')
              return <div> {userName}</div>
          })

          現(xiàn)在,無論你單擊多少次按鈕,都僅在必要時(shí)渲染。

          unsetunset7. JavaScript + CSSunsetunset

          在編寫React應(yīng)用程序時(shí)避免使用原始JavaScript,因?yàn)榻M織CSS比組織JS要困難得多。

          // CSS FILE

          .body {
            height10px;
          }

          //JSX

          return <div className='body'>

          </div>

          const bodyStyle = {
            height"10px"
          }

          return <div style={bodyStyle}>

          </div>

          unsetunset8. 使用對象解構(gòu)unsetunset

          假設(shè)你需要顯示用戶的詳細(xì)信息,

          return (
            <>
              <div> {user.name} </div>
              <div> {user.age} </div>
              <div> {user.profession} </div>
            </>
            
          )

          const { name, age, profession } = user;

          return (
            <>
              <div> {name} </div>
              <div> {age} </div>
              <div> {profession} </div>
            </>
            
          )

          unsetunset9.字符串prop不需要大括號unsetunset

          在將字符串props傳遞給子組件時(shí),

          return(
            <Navbar title={"My Special App"} />
          )

          return(
            <Navbar title="My Special App" />  
          )

          unsetunset10. 從JSX刪除JS代碼unsetunset

          將不能用于渲染或UI功能的JS代碼移出JSX。

          return (
            <ul>
              {posts.map((post) => (
                <li onClick={event => {
                  console.log(event.target, 'clicked!'); // <- THIS IS BAD
                  }} key={post.id}>
          {post.title}
                </li>
              ))}
            </ul>
          );

          const onClickHandler = (event) => {
             console.log(event.target, 'clicked!'); 
          }

          return (
            <ul>
              {posts.map((post) => (
                <li onClick={onClickHandler} key={post.id}> {post.title} </li>
              ))}
            </ul>

          );

          unsetunset11. 使用模板字面量unsetunset

          使用模板字面量生成大字符串。避免使用字符串串聯(lián)。這樣會更干凈。

          const userDetails = user.name + "'s profession is" + user.proffession

          return (
            <div> {userDetails} </div>  
          )

          const userDetails = `${user.name}'s profession is ${user.proffession}`

          return (
            <div> {userDetails} </div>  
          )

          unsetunset12. 按順序?qū)?span style="align-items: unset;background-attachment: scroll;background-clip: border-box;background-image: none;background-origin: padding-box;background-position: 0% 0%;background-repeat: no-repeat;background-size: auto;border-style: none;border-width: 1px;border-color: rgb(0, 0, 0);border-radius: 0px;box-shadow: none;color: rgb(0, 0, 0);display: none;flex-direction: unset;float: unset;height: auto;justify-content: unset;letter-spacing: 0px;line-height: 1.5em;overflow: unset;text-indent: 0em;text-shadow: none;transform: none;width: auto;-webkit-box-reflect: unset;">unsetunset

          始終按特定順序?qū)雰?nèi)容。這樣可提高代碼可讀性。

          經(jīng)驗(yàn)法則是保持這樣的導(dǎo)入順序:

          • 內(nèi)置
          • 外部
          • 內(nèi)部

          所以上面的例子變成了:

          import React from 'react';

          import { PropTypes } from 'prop-types';
          import styled from 'styled-components/native';

          import ErrorImg from '../../assets/images/error.png';
          import colors from '../../styles/colors';

          unsetunset13. 使用隱式返回unsetunset

          使用JavaScript功能中的隱式return來編寫漂亮的代碼。

          假設(shè)我們想要函數(shù)執(zhí)行簡單的計(jì)算并返回結(jié)果。

          const add = (a, b) => {
            return a + b;
          }

          const add = (a, b) => a + b;

          unsetunset14. 組件命名unsetunset

          始終對組件應(yīng)用PascalCase命名約定,對實(shí)例應(yīng)用CamelCase命名約定。

          import reservationCard from './ReservationCard';

          const ReservationItem = <ReservationCard />;

          import ReservationCard from './ReservationCard';

          const reservationItem = <ReservationCard />;

          unsetunset15. 保留prop命名unsetunset

          不要使用DOM組件prop名稱在組件之間傳遞props,因?yàn)槠渌丝赡懿恍枰@些名稱。

          <MyComponent style="dark" />

          <MyComponent className="dark" />

          <MyComponent variant="fancy" />

          unsetunset16. 引號unsetunset

          對JSX屬性使用雙引號,而對所有其他的JS使用單引號。

          <Foo bar='bar' />

          <Foo style={{ left: "20px" }} />

          <Foo bar="bar" />

          <Foo style={{ left: '20px' }} />

          unsetunset17. prop命名unsetunset

          prop命名使用camelCase,如果prop值是React組件,則使用PascalCase。

          <Component
            UserName="hello"
            phone_number={12345678}
          />

          <MyComponent
            userName="hello"
            phoneNumber={12345678}
            Component={SomeComponent}
          />

          unsetunset18. 括號中的JSXunsetunset

          如果組件跨越多行,記得用括號括起來。

          return <MyComponent variant="long">
                     <MyChild />
                   </MyComponent>
          ;

          return (
              <MyComponent variant="long">
                <MyChild />
              </MyComponent>

          );

          unsetunset19. 自關(guān)閉標(biāo)簽unsetunset

          如果組件沒有任何子組件,則使用自結(jié)束標(biāo)記??商岣呖勺x性。

          <SomeComponent variant="stuff"></SomeComponent>

          <SomeComponent variant="stuff" />

          unsetunset20. 方法名稱中的下劃線unsetunset

          不要在任何內(nèi)部React方法中使用下劃線。

          const _onClickHandler = () => {
            // do stuff
          }

          const onClickHandler = () => {
            // do stuff
          }

          unsetunset21. alt propunsetunset

          始終在<img>標(biāo)簽中包含altprop。

          并且不要在alt屬性中使用pictureimage,因?yàn)槠聊婚喿x器已經(jīng)將img元素宣布為圖像。

          <img src="hello.jpg" />

          <img src="hello.jpg" alt="Picture of me rowing a boat" />

          <img src="hello.jpg" alt="Me waving hello" />

          unsetunset結(jié)論unsetunset

          恭喜你,又學(xué)到了新的東西!

          編程快樂!:D

          瀏覽 202
          1點(diǎn)贊
          評論
          收藏
          分享

          手機(jī)掃一掃分享

          分享
          舉報(bào)
          評論
          圖片
          表情
          推薦
          1點(diǎn)贊
          評論
          收藏
          分享

          手機(jī)掃一掃分享

          分享
          舉報(bào)
          <kbd id="afajh"><form id="afajh"></form></kbd>
          <strong id="afajh"><dl id="afajh"></dl></strong>
            <del id="afajh"><form id="afajh"></form></del>
                1. <th id="afajh"><progress id="afajh"></progress></th>
                  <b id="afajh"><abbr id="afajh"></abbr></b>
                  <th id="afajh"><progress id="afajh"></progress></th>
                  黄色强奸免费小视频网站 | 高潮视频在线免费观看 | 日韩一区二区三区黄片 | 成人摸在线 | 操欧美逼|