React 16.3 类方法与构造函数方法

san*_*oon 5 javascript class reactjs

我正在学习 React 16.3,它是新的 Context API。特别是从嵌套组件更新上下文。在他们的示例中,他们设置了一个在构造函数中定义的方法而不是标准方法。

class App extends React.Component {
  constructor(props) {
    super(props);

    // What is the benefit of doing this here?
    this.toggleTheme = () => {
      this.setState(state => ({
        theme:
          state.theme === themes.dark
            ? themes.light
            : themes.dark,
      }));
    };

    this.state = {
      theme: themes.light,
      toggleTheme: this.toggleTheme,
    };
  }

  render() {
    // The entire state is passed to the provider
    return (
      <ThemeContext.Provider value={this.state}>
        <Content />
      </ThemeContext.Provider>
    );
  }
}
Run Code Online (Sandbox Code Playgroud)

我读过的关于提升状态和将方法传递给孩子的所有内容都是使用以下模式完成的。为什么以上优先于以下?有什么区别吗?

class App extends React.Component {
  constructor(props) {
    super(props);

    this.state = {
      theme: themes.light,
      toggleTheme: this.toggleTheme,
    };
    this.toggleTheme = this.toggleTheme.bind(this);

  }

    // Could it be done here?
    toggleTheme() {
        this.setState(state => ({
            theme:
                state.theme === themes.dark
                ? themes.light
                : themes.dark,
        }));
    };


  render() {
    // The entire state is passed to the provider
    return (
      <ThemeContext.Provider value={this.state}>
        <Content />
      </ThemeContext.Provider>
    );
  }
}
Run Code Online (Sandbox Code Playgroud)

Tee*_*eez 2

如果您使用第一种方法,即在构造函数内定义方法,如下所示

constructor() {
    this.toggleTheme = () => {
      this.setState(state => ({
        theme:
          state.theme === themes.dark
            ? themes.light
            : themes.dark,
      }));
    };
}
Run Code Online (Sandbox Code Playgroud)

然后,当您的组件用作this.toggleTheme 回调时,您不必将其引用绑定this到定义它的当前组件,例如this.toggleTheme = this.toggleTheme.bind(this),另一方面,如果您toggleTheme像第二个示例一样在构造函数外部定义为方法,如果作为回调传递toggleTheme,您将在调用时得到“setState is not Define”或类似的信息toggleTheme

此外,第一种方法toggleTheme作为实例属性添加到组件类中,这意味着每个组件实例将有一个单独的 副本toggleTheme,而第二种方法会将其添加到组件类的原型中,这在内存消耗方面更好,因为所有组件实例都将在原型上共享该方法