It may be the 50 React + TypeScript specifications and experiences you need(4)

March 30, 2023 1332hotness 0likes 0comments

31. SetState may be synchronous

  • setState is "asynchronous" in compositing events and hook functions in react.
  • setState is synchronized in native events and setTimeout.

32. Do not add await before setState

  • setState can also be preceded by await and become synchronized, but it is a coincidence that we are not sure which version will not support it in the future. In order to follow the design principles of the react framework, we use the form of drop function.
// bad
func = async (name, value, status) => {
  await this.setState({
    name
  });
  // TODO
};

// good
func = (name, value, status) => {
  this.setState(
    {
      name
    },
    () => {
      // TODO
    }
  );
};

33. Block event default behavior

  • you cannot block the default behavior in React by returning false. PreventDefault must be explicitly called.

34. A function that removes side effects in componentWillUnmount

  • clear EventListener
  • abort a data request
  • clear timer

35. key

  • for key optimization in components, maximize reuse of dom
//bad
this.state.dataAry.map((item, index) => {
  return <span key={index} />;
});

//good
this.state.dataAry.map(item => <span key={item.id} />);

36. There must be hasOwnProperty judgment in for-in (that is, it is forbidden to read the properties of prototype objects directly)

//bad
const arr = [];
const key = '';

for (key in obj) {
  arr.push(obj[key]);
}

//good
const arr = [];
const key = '';

for (key in obj) {
  if (obj.hasOwnProperty(key)) {
    arr.push(obj[key]);
  }
}

37. The use of third-party library functions

  • wrapped in try catch to prevent errors in the third-party library, causing the whole program to crash
/*
 * Echart is used to draw diagrams on behalf of others, but when errors occur in itself, it may affect the execution of business code
 */
// bad
const iniDom = document.getElementById('init-container');
const echartObj = echarts.init(iniDom);
this.setState(
  {
    echartObj
  },
  () => {
    const { echartObj } = this.state;
    // Update Chart
    echartObj.setOption(CHART_CONFIG, true);
  }
);

// good
try {
  const iniDom = document.getElementById('init-container');
  const echartObj = echarts.init(iniDom);
  this.setState(
    {
      echartObj
    },
    () => {
      const { echartObj } = this.state;
      // Update Chart
      echartObj.setOption(CHART_CONFIG, true);
    }
  );
} catch (error) {
  // TODO
}

38. Prevent xss attacks

  • input,textarea and other tags. Do not directly render the html text on the page, filter it with xssb and then output it to the tag.
import { html2text } from 'xss';
render(){
  <div
  dangerouslySetInnerHTML={{
    __html: html2text(htmlContent)
  }}
/>
}

39. Get the real dom in the component

  • use the createRef () function after version 16
class MyComponent extends React.Component<iProps, iState> {
  constructor(props) {
    super(props);
    this.inputRef = React.createRef();
  }

  render() {
    return <input type="text" ref={this.inputRef} />;
  }

  componentDidMount() {
    this.inputRef.current.focus();
  }
}

40. Reduce magic numbers

  • when writing code, try to reduce some unknown numbers and use English words as much as possible. For example, when type = 0, some actions are done, and people don't know why.
// bad
if (type !== 0) {
  // TODO
}

// good
const STATUS: Record<string, any> = {
  READY: 0,
  FETCHING: 1,
  FAILED: 2
};

if (type === STATUS.READY) {
  // TODO
}

// best
enum STATUS {
  // ready
  READY = 0,
  // On request
  FETCHING = 1,
  // request was aborted
  FAILED = 2,
}

InterServer Web Hosting and VPS

Aaron

Hello, my name is Aaron and I am a freelance front-end developer

Comments