旧版本的 context API 的 shouldComponentUpdate 问题
import React, { Component } from 'react';
import PropTypes from 'prop-types';
class CComponent extends Component {
static contextTypes = {
color: PropTypes.string
}
render() {
return (
<span>{this.context.color}</span>
);
}
}
class MComponent extends Component {
shouldComponentUpdate() {
return false;
}
render() {
return (
<CComponent />
);
}
}
class Root extends Component {
static childContextTypes = {
color: PropTypes.string
}
getChildContext() {
return {
color: 'red',
}
}
render() {
return (
<MComponent />
);
}
}
import React, { Component } from 'react';
import PropTypes from 'prop-types';
class CComponent extends Component {
static contextTypes = {
color: PropTypes.string
}
render() {
return (
<span>{this.context.color}</span>
);
}
}
class MComponent extends Component {
static childContextTypes = {
color: PropTypes.string
}
getChildContext() {
return {
color: 'blue',
}
}
render() {
return (
<CComponent onClick={this.props.onClick} />
);
}
}
class Root extends Component {
static childContextTypes = {
color: PropTypes.string
}
getChildContext() {
return {
color: 'red',
}
}
render() {
return (
<MComponent />
);
}
}
import React, { Component, createContext } from 'react';
export const themes = {
light: {
foreground: '#000000',
background: '#eeeeee',
},
dark: {
foreground: '#ffffff',
background: '#222222',
},
};
export const ThemeContext = createContext({
theme: themes.dark,
toggleTheme: () => {},
});
function ThemeTogglerButton(props) {
// The Theme Toggler Button receives not only the theme
// but also a toggleTheme function from the context
return (
<ThemeContext.Consumer>
{({theme, toggleTheme}) => (
<button
onClick={toggleTheme}
style={{backgroundColor: theme.background}}>
Toggle Theme
</button>
)}
</ThemeContext.Consumer>
);
}
// An intermediate component that uses the ThemedButton
class Toolbar extends Component {
shouldComponentUpdate() {
return false
}
render() {
return (
<ThemeTogglerButton onClick={this.props.changeTheme}>
Change Theme
</ThemeTogglerButton>
);
}
}
class App extends Component {
constructor(props) {
super(props);
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}>
<Toolbar changeTheme={this.toggleTheme} />
</ThemeContext.Provider>
);
}
}
如果组件的层级只有几层的话,不建议采用 Context
使用新版本 Context API 取代 Redux?