Sarrafa yanayi a cikin React muhimmin al'amari ne na sarrafa bayanai masu ƙarfi da aiki tare da mu'amalar masu amfani. Jiha tana wakiltar yanayin ɓangaren yanzu kuma yana iya canzawa yayin aiwatar da aikace-aikacen.
A cikin React, jiha wani abu ne na JavaScript wanda ke riƙe da mahimman bayanai waɗanda wani ɓangaren ke buƙatar adanawa da gyara su akan lokaci. Lokacin da jihar ta canza, React ta atomatik sabunta yanayin mai amfani don nuna waɗannan canje-canje.
Don sarrafa jiha a cikin React, muna amfani da kadara ta musamman da ake kira state
. Muna bayyana jihar a cikin maginin sashin kuma mu fara ƙimar farko. Bayan haka, zamu iya canza darajar jihar ta amfani da setState()
hanyar.
Misali, bari mu yi la'akari da sassauƙan Counter:
import React, { Component } from 'react';
class Counter extends Component {
constructor(props) {
super(props);
this.state = {
count: 0
};
}
incrementCount =() => {
this.setState(prevState =>({
count: prevState.count + 1
}));
}
render() {
return(
<div>
<p>Count: {this.state.count}</p>
<button onClick={this.incrementCount}>Increment</button>
</div>
);
}
}
export default Counter;
A cikin misalin da ke sama, muna ayyana jihar da ake kira count
tare da ƙimar farko ta 0. Lokacin da mai amfani ya danna maɓallin "Ƙara", ƙimar count
yana ƙaruwa da ɗaya ta amfani da setState()
hanyar.
Gudanar da jihar yana ba mu damar canza abun ciki da halayen wani yanki dangane da halin yanzu. Wannan yana da amfani lokacin ƙirƙirar abubuwa masu ƙarfi da hulɗa tare da mai amfani.