I Love ReactJS

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

31. SetState may be synchronous

32. Do not add await before setState

// 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

34. A function that removes side effects in componentWillUnmount

35. key

//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

/*
 * 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

import { html2text } from 'xss';
render(){
  <div
  dangerouslySetInnerHTML={{
    __html: html2text(htmlContent)
  }}
/>
}

39. Get the real dom in the component

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

// 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,
}

Exit mobile version