Error handling in React best practices

后端 未结 4 656
别跟我提以往
别跟我提以往 2020-12-13 13:15

When rendering a component in React (with many subcomponents) and a JS error is thrown for whatever reason, what\'s the best way to handle this? Sure I can catch the error

4条回答
  •  [愿得一人]
    2020-12-13 13:45

    Ideally you shouldn't ever have something that would cause a js error. We don't live in a perfect world though so heres a few things I would do to help mitigate them.

    Think about how the code you're writing could break
    if you are calling a method on a variable, think, "is this always going to be this datatype?"

    handleClick = (e) => {
      e && e.preventDefault()
      // code here
    }
    
    handleSomething = (data) => {
      if (Array.isArray(data)) {
        data.reduce(...) // we know this will be here
      }
    }
    

    When making variables, use default values.
    Meaning const { loading = false, data = [] } = this.props. This will help in data type consistencies.

    Handle asynchronous data more elegantly
    Make sure to handle the pending / waiting state of your component. You could (for instance) use a Loading component that renders the content when loaded.

    render() {
      const { data = [] } = this.props
      return (
         0}>
          
        
      )
    }
    

    Where the loading component would be something like.

    const Loading = ({ children, loading = false, message = 'Loading...' }) => {
      if (loading) {
        return {message}
      }
      return children
    }
    

    You should catch exceptions
    If you're writing something that you think could break or if you just want to be overly cautious you can use try catch blocks to catch exceptions in functional components.

    const MyComponent = ({ data = [] }) => {
      try {
        return 
      {data.map( item =>
    • {item}
    • )
    } catch (error) { const message = error.message || 'I broke!' return {message} } }

    In class components you can use

    componentDidCatch(error, errorInfo) {
      // Handle error here.
    }
    

    The docs have a ton of great info if you'd like to learn more

    Now, this is just a rudimentary example to describe what I am talking about. But it will help reduce your JS exceptions, which (when uncaught) will break your single page application. So you need to handle them.
    If a URL is invalid redirect to a 404 page. If a component needs data then wait for the data to render it. If you are trying to access a property on an object that is nested (especially if its from the server), aka this.props.myData.obj.something.somethingelse. Chances are that that object path wont always be there. You need to ensure that each of those aren't undefined or null.

    Extra credit
    I've used lodash's get helper, which has helped me reduce exceptions!

    _.get(this.props, 'myData.obj.something.somethingelse') // returns `undefined` if the path is invalid
    

    I guess the moral of the story is you should be proactive in your code to capture things that could break. :)

提交回复
热议问题