These documents are old and will not be updated. Go toreaguj.devfor new React documents.
These new documentation pages teach modern React and include live examples:
This page introduces the concept of states and lifecycles in a React component. here you canmore detailed information about the API for componentsmeet.
Let's look at an example of a program clockprevious sectionAbout. no chapterrendering elements, we learned only one way to update the UI. We callroot.render()
to change the rendered output:
untilsource=ReactDOM.criarRoot(document.getElementById('source')); function marking() { untilelement= ( <dz> <h1>Hello World!h1> <h2>That's it{novo Data().doLocaleTimeString()}.h2> dz> );source.rendering(element);}set range(marking, 1000);
In this section, we'll learn how to do that.Clock
Make the component truly reusable and independent. Set your own timer and update every second.
We can start by describing what the watch looks like:
untilsource=ReactDOM.criarRoot(document.getElementById('source'));function Clock(props) { turn back ( <dz> <h1>Hello World!h1> <h2>That's it{props.data.doLocaleTimeString()}.h2> dz> );}function marking() {source.rendering(<Clock data={novo Data()} />);}set range(marking, 1000);
However, a fundamental requirement is missing: the fact thatClock
creating a timer and updating the UI every second should be an implementation detailClock
To be.
Ideally, we'd like to write it just once andClock
let the update run by itself:
source.rendering(<Clock />);
To implement it, we needClock
Add "Status" to the component.
State is similar to props but is private and fully controlled by the component.
We already havepreviously mentionedthat components defined as classes have some additional characteristics. Local State is just that: a resource only available in class.
Casting from a function to a class
component likeClock
you can convert to a class in five steps:
- create aclasse ES6with the same name, that is
React.Component
expanded. - Create an empty method called
render()
. - Move function content to
render()
Method. - to replace
props
zit.props
crender()
Method. - Remove any remaining empty function declarations.
classroom Clock stretches to react.Hey { rendering() { turn back ( <dz> <h1>Hello World!h1> <h2>That's it{Dez.props.data.doLocaleTimeString()}.h2> dz> ); }}
Clock
it is now defined as a class, not a function.
To dierendering
the method is called every time there is an update, but as long as
render on same DOM node, just one instanceClock
used class. This allows us to use additional features such as local state and lifecycle methods.
Add a local state to the class
we postponeddata
from props to condition in three steps:
- to replace
ta.rekwizyty.data
zdez.stan.data
crender()
Method:
classroom Clock stretches to react.Hey { rendering() { turn back ( <dz> <h1>Hello World!h1> <h2>That's it{Dez.country.data.doLocaleTimeString()}.h2> dz> ); }}
- add adesigner classadded to initial
This status
attributes:
classroom Clock stretches to react.Hey { constructor(props) { Super(props); Dez.country= {data: novo Data()}; } rendering() { turn back ( <dz> <h1>Hello World!h1> <h2>That's it{Dez.country.data.doLocaleTimeString()}.h2> dz> ); }}
notice how weprops
passed to the base constructor:
constructor(props) { Super(props); Dez.country= {data: novo Data()}; }
Class components must always include a base constructorprops
to call.
- remove it
data
Prop vom
Element:
source.rendering(<Clock />);
Later, we'll paste the timer code back into the component.
The result looks like this:
classroom Clock stretches to react.Hey { constructor(props) { Super(props); Dez.country= {data: novo Data()}; } rendering() { turn back ( <dz> <h1>Hello World!h1> <h2>That's it{Dez.country.data.doLocaleTimeString()}.h2> dz> ); }}untilsource=ReactDOM.criarRoot(document.getElementById('source'));source.rendering(<Clock />);
So let's be sureClock
sets your own timer and updates every second.
Add Lifecycle Methods to the Class
In applications with many components, it is important to free up resources when a component is removed.
we want onecreate timers, SeClock
is rendered to the DOM for the first time. This is called "assembly" in React.
we also wanttimers removedit will be if it is zClock
the created DOM element is removed. In React, this is called "disassembly".
We can declare special methods in a component class to execute specific code when assembling and disassembling:
classroom Clock stretches to react.Hey { constructor(props) { Super(props); Dez.country= {data: novo Data()}; } componenteDidMount() { } component will be disassembled() { } rendering() { turn back ( <dz> <h1>Hello World!h1> <h2>That's it{Dez.country.data.doLocaleTimeString()}.h2> dz> ); }}
These methods are called "lifecycle methods".
To dieDidMount() component
The method runs after the components have been rendered into the DOM. This is a good place to put the timer:
componenteDidMount() { Dez.timer id= set range( () => Dez.marking(), 1000 ); }
Notice how we put the timer IDDez
(ten.identifier timera
) save to your computer.
One secondit.props
configured by React i itselfThis status
has a special meaning, you can manually add additional fields to the class if you want to store something that doesn't participate in the data stream (timer ID for example).
We will use a timer incomponenteWillDesmontar()
Cancel lifecycle method:
component will be disassembled() { clear range(Dez.timer id); }
Finally, we'll add a method calledmarking
implement itClock
it will ring every second.
she goesthis.setState()
use to schedule component local state update:
classroom Clock stretches to react.Hey { constructor(props) { Super(props); Dez.country= {data: novo Data()}; } componenteDidMount() { Dez.timer id= set range( () => Dez.marking(), 1000 ); } component will be disassembled() { clear range(Dez.timer id); } marking() { Dez.define state({ data: novo Data() }); } rendering() { turn back ( <dz> <h1>Hello World!h1> <h2>That's it{Dez.country.data.doLocaleTimeString()}.h2> dz> ); }}untilsource=ReactDOM.criarRoot(document.getElementById('source'));source.rendering(<Clock />);
Now the clock is ticking every second.
Let's quickly summarize what's going on here and the order in which the methods are called:
- Se
someroot.render()
is provided, React calls the constructorClock
item up. ThereClock
needs to display the current time, initialize itThis status
with an object containing the current time. We will update this status later. - react then call
render()
methodClock
item up. This is how React knows what to show on the screen. React then updates the DOM according to the rendered outputClock
. - if you leave
Clock
inserted into the DOM, React calls LifecycleDidMount() component
ABOUT. Including calls toClock
component to create a browser on a timer that every secondmarking()
method calls. - Every second the browser calls a method
marking()
linked method. As part of these plansClock
a component that updates the user interface where thissetState()
connection to the object containing the current time. thanks tosetState()
-call, React knows the state has changed and calls itrender()
methods of relearning what should be displayed on the screen. this time willdez.stan.data
crender()
the method must be different and the rendered content contains the updated time. React updates the DOM accordingly. - Se
Clock
component is always removed from the DOM, React calls the methodcomponenteWillDesmontar()
The lifecycle method and timer stop.
Use states correctly
There are three things you care aboutsetState()
should know.
Do not edit state directly
This will not re-render the component, for example:
// MalDez.country.comment= 'Hey';
use insteadsetState()
:
// ValidDez.define state({comment: 'Hey'});
The only place where you areThis status
you can define is the constructor.
Status updates can be asynchronous
For performance reasons, React may do somesetState()
Combine conversations into one update.
EUit.props
EUThis status
can be updated asynchronously, do not rely on the ability to use the values for next-state calculations.
For example, this code cannot update the counter.
// MalDez.define state({ lada: Dez.country.lada+ Dez.props.increase,});
To avoid this, we use the second formsetState()
which takes a function instead of an object. This function takes the previous state as the first argument and the props at the time of the update as the second argument:
// ValidDez.define state((country,props) => ({ lada:country.lada+props.increase}));
we have one upstairslambda functionused, but the normal functions also work:
// ValidDez.define state(function(country,props) { turn back { lada:country.lada+props.increase};});
Status updates are merged
if yousetState()
calls, React will bind the given object to the current state.
For example, your state can contain several independent variables:
constructor(props) { Super(props); Dez.country= { posts: [], comments: [] }; }
So you can use them independently in differentsetState()
-Update connections.
componenteDidMount() { downloading posts().Then(responder => { Dez.define state({ posts:responder.posts }); }); Download comments().Then(responder => { Dez.define state({ comments:responder.comments }); }); }
The connection is only superficial andthis.setState({comentar})
sheetsthis.status.posts
they exist but have been replacedthis.state.comments
.
Top-down data flow
Neither parent nor child components can know whether a given component is stateful or stateless, nor should they care whether it is defined as a function or a class.
Therefore, the state is often referred to as local or closed. It is only available to the component that owns and creates it. For any other ingredient.
A component can choose whether to pass its state as props:
<h2>That's it{Dez.country.data.doLocaleTimeString()}.h2>
This also works for custom components:
<formatted date data={Dez.country.data} />
To dieformatted date
leverage ingredientdata
as a prop and I don't know if it's from the state or propsClock
comes from or was entered manually:
function formatted date(props) { turn back <h2>That's it{props.data.doLocaleTimeString()}.h2>;}
This is commonly referred to as "top-down" or "one-way" data flow. Each state always belongs to a specific component, and any data or UI derived from that state can only affect all "lower" components in the tree.
If you think of the component tree as a supporting cascade, each component state is like an additional source of water that flows from a random location and goes down with it.
To show that all elements are really independent, let's create aApplication
component three
rendering:
function Application() { turn back ( <dz> <Clock /> <Clock /> <Clock /> dz> );}
AllClock
creates its own timer and updates automatically.
In React Apps, component implementation details that may change over time are considered stateless or stateful. You can use stateless components inside stateful components and vice versa.