【发布时间】:2019-03-05 11:03:31
【问题描述】:
我对新的 React Context-api 有两个问题:
- React 文档有以下示例Updating context from a nested component。在构造函数中声明 toggleTheme 函数(而不是作为类方法)是否有某些特定原因?
import {ThemeContext, themes} from './theme-context';
import ThemeTogglerButton from './theme-toggler-button';
class App extends React.Component {
constructor(props) {
super(props);
this.toggleTheme = () => {
this.setState(state => ({
theme:
state.theme === themes.dark
? themes.light
: themes.dark,
}));
};
// State also contains the updater function so it will
// be passed down into the context provider
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>
);
}
}
function Content() {
return (
<div>
<ThemeTogglerButton />
</div>
);
}
ReactDOM.render(<App />, document.root);
- 在许多示例中,Provider-component 的值是 high-up-component 的状态(就像上面的示例一样)。这意味着每次我想更新 Context-value 时,我都需要更新 high-up 组件的状态。这意味着 high-up 组件在状态更新时重新渲染,这反过来意味着它的所有子组件也重新渲染。但我想要的只是让消费者组件监听该提供者组件重新渲染。现在,每次我更新 Context-value 时,基本上整个应用程序都会重新渲染......我错过了什么吗?
【问题讨论】:
标签: reactjs