Network Security Internet Technology Development Database Servers Mobile Phone Android Software Apple Software Computer Software News IT Information

In addition to Weibo, there is also WeChat

Please pay attention

WeChat public account

Shulou

How Context-React accesses data across components

2025-03-13 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >

Share

Shulou(Shulou.com)06/02 Report--

This article is about how Context-React accesses data across components. The editor thinks it is very practical, so share it with you as a reference and follow the editor to have a look.

Context provides a way to access data across components. It does not need to transfer properties layer by layer between component trees, and it can easily access the data of other components.

In a classic React application, the data is transmitted by the parent component to the child component through props. However, in some specific situations, some data needs to be shared between components. Context provides us with a way to share data between components, which can avoid passing data layer by layer on the component tree.

Situations where Context is used

Context can share "global" data among components of the component tree. For example: login user information, user-selected theme, language, and so on. In the following example, we "manually" pass the theme attribute from top to bottom to style the 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

}

}

With Context, we can avoid passing props through multiple intermediate components

/ / 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

}

}

Sometimes, some data needs to be accessed by many components, and these components are on different levels of the component tree. Context allows us to share data changes in various components in the form of "broadcast"

Context related API

React.createContext

Const MyContext = React.createContext (defaultValue); copy code

Create a new Context object. When React renders a component and the component registers Context, it reads the context value of the Provider component closest to that component in the parent component

DefaultValue is used only if the "Consumer" component cannot find the Provider component.

Context.Provider

Copy the code

Each Context object carries a React component called Provider. Provider allows the "Consumer" component to listen for changes to context

By passing the prop of value to the descendant Consumer components of Provider, a Provider can establish relationships with multiple Consumer components.

All descendant Consumer components will be re-rendered when the value property of Provider is updated. This update propagates from Provider to its descendant Consumer components, but does not trigger the shouldComponentUpdate method. So even if the ancestor component of the Consumer component is not updated, the Consumer component will update.

Context uses the same algorithm as Object.is to compare the new and old values of value to determine whether its value has been updated

Be careful

This way of determining whether the value has changed can cause problems when passing objects to the value.

Class.contextType

Class MyClass extends React.Component {

ComponentDidMount () {

Let value = this.context

/ perform a side-effect at mount using the value of MyContext /

}

ComponentDidUpdate () {

Let value = this.context

/... /

}

ComponentWillUnmount () {

Let value = this.context

/... /

}

Render () {

Let value = this.context

/ render something based on the value of MyContext /

}

}

MyClass.contextType = MyContext

After assigning a Context object to the contextTpe property of class, we can get the method of the current Context object in each declaration cycle function of the component through this.context

Note:

In this way, only one context object can be registered per component. If you need to read the value of multiple context

If the syntax from the ES experiment is used in the coding, you can initialize the contextTYpe. Exe using a static (static) member of the class. The code is as follows:

Class MyClass extends React.Component {

Static contextType = MyContext

Render () {

Let value = this.context

/ render something based on the value /

}

}

Context.Consumer

{value = > / render something based on the context value /}

Consumer is a React component that listens for context changes. It allows us to listen for contxt changes in a function component.

The Consumer component requires that its child elements be a function. The argument to this function receives the value of the current context, requiring that the parameter value passed to the function by a React node (node) is equal to the context value of the outer Provider component closest to this Consumner. If there is no outer Provider component, it is equal to the parameter value passed when createContext () is called (the default value of context).

Be careful

More information about "child elements are a function"

Chestnut

Update Context in nested components

In development, we often need to update the value of context on some components with deeply nested structures. At this point, we can pass down a function to update the value of context. The code is as follows:

Theme-context.js

/ / Make sure the shape of the default value passed to// createContext matches the shape that the consumers roomtexports const ThemeContext = React.createContext ({

Theme: themes.dark

ToggleTheme: () = > {}

});

Theme-toggler-button.js

Import {ThemeContext} from'. / theme-context'

Function ThemeTogglerButton () {

/ / The Theme Toggler Button receives not only the theme

/ / but also a toggleTheme function from the context

Return (

{({theme, toggleTheme}) = > (

Toggle Theme

)}

);

}

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 providerthis.state = {theme: themes.light, toggleTheme: this.toggleTheme,}

}

Render () {

/ / The entire state is passed to the provider

Return (

);

}

}

Function Content () {

Return (

);

}

ReactDOM.render (, document.root)

Use multiple Contexts

To maintain the fast rendering of React, we need to write each consumer component as a separate component node (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 valuesreturn ()

}

}

Function Layout () {

Return (

);

}

/ / A component may consume multiple contexts

Function Content () {

Return (

{theme = > (

{user = > (

)}

)}

);

}

If there are more than two context often used together, we need to consider creating one render prop component to provide two Context together.

Be careful

Because context uses reference markers (reference identity) to determine when re-rendering is needed, in some cases, non-internal rendering of consumer is triggered when the parent element of provider is re-rendered. For example, the following code re-renders all consumer components each time Provider re-renders. Because a new object is always created to assign a value to value (value is always changing)

Class App extends React.Component {

Render () {

Return (

);

}

}

To avoid this problem, you can put the value in the state of the component

Class App extends React.Component {

Constructor (props) {

Super (props)

This.state = {

Value: {something: 'something'}

}

}

Render () {

Return (

);

}

}

Thank you for reading! This is the end of the article on "how Context-React accesses data across components". I hope the above content can be of some help to you, so that you can learn more knowledge. if you think the article is good, you can share it for more people to see!

Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.

Views: 0

*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.

Share To

Development

Wechat

© 2024 shulou.com SLNews company. All rights reserved.

12
Report