Home > Web Front-end > JS Tutorial > 4 Practical Tips for Developing React Apps

4 Practical Tips for Developing React Apps

青灯夜游
Release: 2020-09-02 15:37:46
forward
4395 people have browsed it

4 Practical Tips for Developing React Apps

[Related topic recommendations: react interview questions (2020)]

Background

Hooks have been very popular since their launch. It has changed the way we write React code and helps us write more concise code.

Today’s article is not about Hooks. In addition to Hooks, there are many practical techniques that can help us write concise and clear code.

Today I have sorted out a few techniques, some of which are also that I have practiced in company projects. Now I have sorted them out to share with you. I hope it will inspire you .

Text

1. Use a string to define a React element

A simple example:

// 我们可以通过把一个字符串'p' 赋值给一个变量, 就像:
import React from 'react'

const MyComponent = 'p'

function App() {
  return (
    
      <mycomponent>
        <h3>I am inside a {'</h3>
<p></p>'} element
      </mycomponent>
    >
  )
}
Copy after login

React will internally call React.createElement and use this string to generate this element.

In addition, you can also explicitly define component to determine the rendered content, for example:

// 定义一个MyComponent
function MyComponent({ component: Component = 'p', name, age, email }) {
  
  return (
    <component>
      <h1>Hi {name} </h1>
      
        <h6>You are {age} years old</h6>
        <small>Your email is {email}</small>
      >
    </component>
  )
}
Copy after login

Applicable method:

function App() {
  return (
    
      <mycomponent>
    >
  )
}</mycomponent>
Copy after login

This method , you can also pass in a custom component, such as:

function Dashboard({ children }) {
  return (
    

      {children}     

  ) } function App() {   return (            <mycomponent>     >   ) }</mycomponent>
Copy after login

If you encounter a similar element or component that handles , you can abstract it in this custom way , simplify your code.

Give a real-life example:

For example, we now need to make a demand for packaging goods. It can be packaged individually or in batches. Custom components can be written for the common points:

import React from 'react'
import withTranslate from '@components/withTranslate'
import PackComponent from './PackComponent'
import usePack, { check } from './usePack'

let PackEditor = (props) => {
  const packRes = usePack(props)
  return (
    <packcomponent></packcomponent>
  )
}

PackEditor = withTranslate(PackEditor)
PackEditor.check = check

export default PackEditor
Copy after login

This way, it can be used flexibly in different business modules, which is very convenient.

2. Define error boundaries

In Javascript, we all use try/catch to catch possible occurrences Exception, handle the error in catch. For example:

function getFromLocalStorage(key, value) {
  try {
    const data = window.localStorage.get(key)
    return JSON.parse(data)
  } catch (error) {
    console.error
  }
}
Copy after login

In this way, even if an error occurs, our application will not crash with a white screen.

React is also Javascript in the final analysis, and there is no difference in essence, so there is no problem in using try/catch in the same way.

However, due to the React implementation mechanism, Javascript errors occurring inside the component will destroy the internal state, and render will generate an error:

https://github.com/facebook/react/ issues/4026

4 Practical Tips for Developing React Apps

Based on the above reasons, the React team introduced Error Boundaries:

https://reactjs.org/docs /error-boundaries.html

Error boundaries, is actually a React component. You can use a component to handle any error information it captures.

When the component tree collapses, your customized UI can also be displayed as a fallback.

Look at the official examples provided by React:
https://reactjs.org/docs/error-boundaries.html#introducing-error-boundaries

class ErrorBoundary extends React.Component {
  constructor(props) {
    super(props)
    this.state = { hasError: false }
  }
  
  static getDerivedStateFromError(error) {
    // Update state so the next render will show the fallback UI.
    return { hasError: true }
  }
  
  componentDidCatch(error, errorInfo) {
    // You can also log the error to an error reporting service
    logErrorToMyService(error, errorInfo)
  }
  
  render() {
    if (this.state.hasError) {
      // You can render any custom fallback UI
      return <h1>Something went wrong.</h1>
    }
    return this.props.children
  }
}
Copy after login

Usage:

<errorboundary>
  <mywidget></mywidget>
</errorboundary>
Copy after login

Live Demo By Dan Abramov:

https://codepen.io/gaearon/pen/wqvxGa?editors=0010

3. High-order components

To put it in layman’s terms, the so-called high-order component is that you throw a component in, add some attributes or operations, and then throw it out.

Generally speaking, you can abstract some components that have in common into a high-order component, and then reuse# in different modules ##.

For example, in our system, there is a type of button that needs to be added with a

border, which is used in many places. We abstract it:

import React from 'react'

// Higher order component
const withBorder = (Component, customStyle) => {
  class WithBorder extends React.Component {
    render() {
      const style = {
        border: this.props.customStyle ? this.props.customStyle.border : '3px solid teal'
      }
      return <component></component>
    }
  }
  
  return WithBorder
}

function MyComponent({ style, ...rest }) {
  return (
    <p>
        </p><h2>
          This is my component and I am expecting some styles.
        </h2>
    
  )
}

export default withBorder(MyComponent, { border: '4px solid teal' })
Copy after login
is decorated withBorder The MyComponent component has the function of unifying the border. If you want to modify it later, you can unify it in this

middle layer, which is very convenient.

In my project, I also use some high-order components. To give a specific example:

PackEditor = withTranslate(PackEditor)
Copy after login
Our

PackEditor is an enhanced component. What features have been added?

As the name expresses,

withTranslate, adds a translation function. Let me show you how this component is implemented:

import React from 'react'
import { Provider } from 'react-redux'
import { injectIntl } from 'react-intl'
import { store } from '@redux/store'
import { Intl } from './Locale'

const withTranslate = BaseComponent => (props) => {
  // avoid create a new component on re-render
  const IntlComponent = React.useMemo(() => injectIntl(
    ({ intl, ...others }) => (
      <basecomponent> { // 注入翻译方法
          if (!id) { return '' }
          return intl.formatMessage(
            typeof id === 'string' ? { id } : id,
            values
          )
        }}
        {...others}
      />
    )
  ), [])

  IntlComponent.displayName = `withTranslate(${BaseComponent.displayName || 'BaseComponent'})`
  
  return (
    <provider>
      <intl>
        <intlcomponent></intlcomponent>
      </intl>
    </provider>
  )
}

export default withTranslate</basecomponent>
Copy after login
The usage is very flexible:

const Editor = withTranslate(({
  // ...
  translate,
}) => {
  // ...
   return (
     
      {translate('xxx')}}
     >
   )
})
Copy after login
Very convenient.

4. Render props

Rrender prop refers to a function that uses a value between React

components The simple technology of prop sharing code is similar to HOC, which is a problem of logic reuse between components. More specifically, the Render prop is a function that tells the component what content

needs to be

rendered. Let’s take a look at a simple example:

The following component tracks the mouse position in a web application:

class Mouse extends React.Component {
  state = { x: 0, y: 0 };

  handleMouseMove = (event) => {
    this.setState({
      x: event.clientX,
      y: event.clientY
    });
  }

  render() {
    return (
      <p>
        </p><p>The current mouse position is ({this.state.x}, {this.state.y})</p>
      
    );
  }
}

class MouseTracker extends React.Component {
  render() {
    return (
      
        <h1>移动鼠标!</h1>
        <mouse></mouse>
      >
    );
  }
}
Copy after login

As the cursor moves across the screen, the component displays its (x ,y) coordinate.

The question now is:

How do we reuse this behavior in another component?

换个说法,若另一个组件需要知道鼠标位置,我们能否封装这一行为,以便轻松地与其他组件共享它 ??

假设产品想要这样一个功能: 在屏幕上呈现一张在屏幕上追逐鼠标的猫的图片。

我们或许会使用

class Cat extends React.Component {
  render() {
    const mouse = this.props.mouse;
    return (
      <img  alt="4 Practical Tips for Developing React Apps" >
    );
  }
}
Copy after login

这个需求如此简单,你可能就直接修改Mouse组件了:

class Mouse extends React.Component {
  state = { x: 0, y: 0 };

  handleMouseMove = (event) => {
    this.setState({
      x: event.clientX,
      y: event.clientY
    });
  }

  render() {
    return (
      <p>
        <cat></cat>
      </p>
    );
  }
}
Copy after login

巴适~ 简单粗暴, 一分钟完成任务。

可是,如果下次产品再要想加条狗呢

以上的例子,虽然可以完成了猫追鼠标的需求,还没有达到以可复用的方式真正封装行为的目标。

当我们想要鼠标位置用于不同的用例时,我们必须创建一个新的组件,专门为该用例呈现一些东西.

这也是 render prop 的来历:

我们可以提供一个带有函数 prop 的 <mouse></mouse> 组件,它能够动态决定什么需要渲染的,而不是将 硬编码 组件里.

修改一下上面的代码:

class Cat extends React.Component {
  render() {
    const mouse = this.props.mouse;
    return (
      <img  alt="4 Practical Tips for Developing React Apps" >
    );
  }
}

class Mouse extends React.Component {
  state = { x: 0, y: 0 };

  handleMouseMove = (event) => {
    this.setState({
      x: event.clientX,
      y: event.clientY
    });
  }

  render() {
    return (
      

        {this.props.render(this.state)}       

    );   } } class MouseTracker extends React.Component {   render() {     return (       

        

移动鼠标!

         (                    )}/>       
Copy after login

    );   } }

提供了一个render 方法,让动态决定什么需要渲染。

事实上,render prop 是因为模式才被称为 render prop ,不一定要用名为 render 的 prop 来使用这种模式。

任何被用于告知组件需要渲染什么内容的函数 prop, 在技术上都可以被称为 "render prop".

另外,关于 render prop 一个有趣的事情是你可以使用带有 render prop 的常规组件来实现大多数高阶组件 (HOC)。

例如,如果你更喜欢使用 withMouse HOC 而不是 组件,你可以使用带有 render prop 的常规 轻松创建一个:

function withMouse(Component) {
  return class extends React.Component {
    render() {
      return (
        <mouse> (
          <component></component>
        )}/>
      );
    }
  }
}</mouse>
Copy after login

也是非常的简洁清晰。

有一点需要注意的是, 如果你在定义的render函数里创建函数, 使用 render prop 会抵消使用 React.PureComponent 带来的优势。

因为浅比较 props 的时候总会得到 false,并且在这种情况下每一个 render 对于 render prop 将会生成一个新的值

class Mouse extends React.PureComponent {
  // 与上面相同的代码......
}

class MouseTracker extends React.Component {
  render() {
    return (
      
        <mouse> ( // 这是不好的! 每个渲染的 `render` prop的值将会是不同的。
          <cat></cat>
        )}/>
      >
    );
  }
}</mouse>
Copy after login

在这样例子中,每次 渲染,它会生成一个新的函数作为 的 prop,因而在同时也抵消了继承自 React.PureComponent 的 组件的效果.

为了绕过这一问题,有时你可以定义一个 prop 作为实例方法,类似这样:

class MouseTracker extends React.Component {
  renderTheCat(mouse) {
    return <cat></cat>;
  }

  render() {
    return (
      <p>
        </p><h1>Move the mouse around!</h1>
        <mouse></mouse>
      
    );
  }
}
Copy after login

5.组件性能

性能优化是永恒的主题, 这里不一一细说, 提供积分资源供你参考:

总结

以上几点都是我们经常要使用的技巧, 简单实用, 分享给大家, 希望能给大家带来一些帮助或启发,谢谢。

推荐阅读:React在线手册

The above is the detailed content of 4 Practical Tips for Developing React Apps. For more information, please follow other related articles on the PHP Chinese website!

source:segmentfault.com
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template