gpt4 book ai didi

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

转载 作者:塔克拉玛干 更新时间:2023-11-02 21:10:14 25 4
gpt4 key购买 nike

我正在学习 React 16.3,它是新的 Context API。特别是Updating Context from a Nested Component .在他们的示例中,他们设置了一个在构造函数中定义的方法,而不是标准方法。

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>
);
}
}

我读到的关于提升状态和将方法传递给 child 的所有内容都是使用以下模式完成的。为什么上面的比下面的更受欢迎?有什么区别吗?

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>
);
}
}

最佳答案

如果你使用第一种方法,像这样在构造函数中定义方法

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

那么当你的组件使用this.toggleTheme 作为回调时,你不必绑定(bind)它的this 对定义它的当前组件的引用,例如this.toggleTheme = this.toggleTheme.bind(this),另一方面,如果您像第二个示例那样将 toggleTheme 定义为构造函数之外的方法,并且如果toggleTheme 被传递作为回调,当 toggleTheme 被调用时你会得到“setState is not defined”或类似的东西

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

关于javascript - React 16.3 类方法与构造函数方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50362535/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com