好程序员web前端分享Context-React跨组件访问数据的利器
  Context提供了一种跨组件访问数据的方法。它无需在组件树间逐层传递属性,也可以方便的访问其他组件的数据
  在经典的React应用中,数据是父组件通过props向子组件传递的。但是在某些特定场合,有些数据需要在各个组件之间共享。Context为我们提供一种组件之间共享数据的方式,可以避免数据在组件树上逐层传递
  使用Context的场合
Context可以在组件树的组件之间共享“全局”数据。例如:登陆的用户信息,用户选择的主题、语言等等。下面的例子中,我们“手动”自上而下传递theme属性,用来设定Button的样式。
class App extends React.Component {
render() {
return ;
}
}
function Toolbar(props) {
// The Toolbar component must take an extra "theme" prop
// and pass it to the ThemedButton. This can become painful
// if every single button in the app needs to know the theme
// because it would have to be passed through all components.
return (




);
}
class ThemedButton extends React.Component {
render() {
return ;
}
}
使用Context,我们可以避免通过多个中间组件传递props
// Context lets us pass a value deep into the component tree// without explicitly threading it through every component.// Create a context for the current theme (with "light" as the default).const ThemeContext = React.createContext('light');
class App extends React.Component {
render() {
// Use a Provider to pass the current theme to the tree below.
// Any component can read it, no matter how deep it is.
// In this example, we're passing "dark" as the current value.
return (



);
}
}

// A component in the middle doesn't have to
// pass the theme down explicitly anymore.
function Toolbar(props) {
return (




);
}

class ThemedButton extends React.Component {
// Assign a contextType to read the current theme context.
// React will find the closest theme Provider above and use its value.
// In this example, the current theme is "dark".
static contextType = ThemeContext;
render() {
return
)}

);
}

export default ThemeTogglerButton;
app.js
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 (



);
}
}

function Content() {
return (




);
}

ReactDOM.render(, document.root);
使用多个Contexts
为了保持React的快速渲染,我们需要将每个consumer组件编写成一个独立的组件节点(node)
// Theme context, default to light themeconst ThemeContext = React.createContext('light');
// Signed-in user contextconst UserContext = React.createContext({
name: 'Guest',
});
class App extends React.Component {
render() {
const {signedInUser, theme} = this.props;

// App component that provides initial context values
return (
  
    
      
    
  
);

}
}

function Layout() {
return (





);
}

// A component may consume multiple contexts
function Content() {
return (

{theme => (

{user => (

)}

)}

);
}
如果有两个以上的context经常一起使用,我们需要考虑创建一个render prop component一并提供两个Context
注意
因为context使用引用标示符(reference identity)来判断何时需要重新渲染,所以有些情况下,当provider的父元素重新渲染时,会触发consumer的非内部渲染。例如下面代码,在每次Provider重新渲染时,会重新渲染所有的consumer组件。因为会一直创建一个新的对象赋值给value(value一直在变)
class App extends React.Component {
render() {
return (



);
}
}
为了避免这个问题,可以将value放在组件的state中
class App extends React.Component {
constructor(props) {
super(props);
this.state = {
value: {something: 'something'},
};
}

render() {
return (



);
}
}