I Love ReactJS

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

21. Simple components can use functions instead of

// bad
class Listing extends React.Component {
  render() {
    return <div>{this.props.hello}</div>;
  }
}

// good
function Listing({ hello }) {
  return <div>{hello}</div>;
}

22. Cache commonly used attributes

// bad
this.props.app.openid;
this.state.time

// good
const { app } = this.props;
const { time } = this.state;
console.log(app.openid)

23. The input input box uses trim ()

// bad
let searchContent = form.search.value;

// good
let searchContent = form.search.value.trim();

24. You need to escape before using location jump

// bad
window.location.href = redirectUrl + '?a=10&b=20';

// good
window.location.href = redirectUrl + encodeURIComponent('?a=10&b=20');

25. Use react-router


// bad
import { withRouter, RouteComponentProps } from 'react-router-dom';

export interface IProps extends RouteComponentProps<any> {}
class App extends React.Component<IProps, AppStates> {}
export default withRouter(App);


// good
import { withRouter, RouteComponentProps } from 'react-router-dom';

class App extends React.Component<IProps & RouteComponentProps<{}>, AppStates> {}
export default withRouter(App);

26. Simultaneous development, data request api directory git conflict directory scheme

// at present

|- api
  |- pageA.ts
  |- pageB.ts

// propose

|- api
  |- pageA
    |- index.js
    |- aaa.js
    |- bbb.js
  |- pageB
    |- index.js
    |- aaa.js
    |- bbb.js
    |- ccc.js

27. Components are too deeply nested

28. The code filters out situations you don't consider

function parse (str:string){
  if (typeof(str) === 'string' ) {

  }
}

29. Asynchronous requests in business code require try catch

getStudentList = async () => {
  try {
    this.setState({
      loading: true,
      isEmpty: false
    });
    await getStudentList({});
  } catch (e) {
    // TODO
    console.log(e)
  } finally {
    //  Some backtracking operations after failure
    this.setState({
      loading: false,
      isEmpty: true
    });
  }
};

30. There are three uses of setState


this.setState({

})

// Function, typically used to perform some operations before setState
this.setState(
  () => {
    // TODO
    console.log('')
    return {
      a:300
    }
  }
)

// The second parameter is generally used to perform some operations after setState
this.setState({
  a:300
}, () => {
  // TODO
})
Exit mobile version