Introduction:

React, for example, focuses on methods of a class. Then draw your sword! Young, is familiar with the taste.

The body of the

0

It is good to advise people to use const, but the following point is more or less a hooligan.

  • Since it remains the same after the function is executed, it should be declared a constant
  • useconstCan prevent a variable from being used repeatedly
  • Declare it a constant, and I can stop paying attention to it.

Let’s look at an example of rendering a table

The data format

export enum ESex {
  man = "man",
  woman = "woman",
}
Copy the code
export interface IHero {
  id: string;
  name: string;
  age: number;
  sex: ESex;
}
Copy the code

Render the name

private renderNameColumn = (name, { sex, id }: IHero) => { const { checkedIdList } = this.state; const checked = checkedIdList.some((key) => key === id); let sexStr = sex === ESex.man ? "Male" : "female "; let color = checked ? "red" : "blue"; return ( <span style={{ color }}> {name} ({sexStr}) </span> ); };Copy the code

Just because it can’t be reassigned doesn’t mean it’s constant if it’s not reassigned

Checked is checked when I write this line, so it’s declared as a constant. The text and color values don’t change, but it’s hard to say what state it determines.

Predictably, text and color are the most likely to be reassigned in a changing business.

For example, IHero added isAnimal, this time to render male and female, can not always expect to write in one line of code.

So it makes sense that checkedIdList declares const, and its state never changes.

1

Each identifier has only one responsibility, and having more than one can confuse logic, which is a big no-no in writing code. Using const is not an indicator. Too many identifiers are declared for one duty, and abuse is worse than not using them.

multi-purposeconstIt is hoped that when coding, programmers can comb out the execution process by thinking about the responsibilities and states of identifiers, so as to plan in advance, so as to achieve a smooth process.

2

Look at an example of adding

  private onHeroAdd = (hero: IHero) => {
    const { dataSource } = this.state;
    let newDataSource = [...dataSource];
    if (hero.sex === ESex.man) {
      newDataSource.push(hero);
    } else {
      newDataSource.unshift(hero);
    }
    this.setState({
      dataSource: newDataSource,
    });
  };
Copy the code

Is newDataSource changed or the same? Const can only limit reassignment.

conclusion

Code specifications should be practical, with an emphasis on helping programmers solve problems rather than restricting them from doing so.

Everyone has a ceiling of his or her abilities. This is a matter of course. Forcing someone to raise their level is tacks of excessive development.