Im new to reactjs. I dont really understand how does props and state work. From my research i have found that props are passed from parent to child. And states can only be used in a single component. But when i see these codes below, i have no idea how it works. Can someone provide me with a good example and explanation. Thanks
Not only that whats the difference between let and var
default class WildList extends React.Component {
constructor(props){
super(props);
this.props = props;
let {keyword, dealstatus} = this.props;
this.state = {
keyword
}
}
}
PS = This WildList class is being used in different component as well.
Simple state is specific to single component. you can define properties within the state. Once you change the state by setstate page will render again. example for props is below.
export default class Devices extends Component {
constructor(props) {
super(props);
this.state = {
userName: "Name 1",
itemCount: 0, // this property can use within the Devices Component not in Device detail
}
}
render() {
.....
//you can pass username to DeviceDetail page
<div>
<DeviceDetail userName={this.state.userName} />
</div>
}
}
//Inside DeviceDetail class
export default class DeviceDetail extends Component {
constructor(props) {
super(props);
this.state = {
userName: props.userName, //you can call username using props
}
}
}
Var vs let
getAllDevices = () => {
var totalDevicesCount = 0; // property is initially in the global scope.
let apiUrl = ....URL
var response = fetch(apiUrl);
const data = response.json();
totalDevicesCount = data.length;
if (data.length > 0) {
this.state.itemCount = totalDevicesCount; // Since this is Var can use inside different block as well but inside this if condition you cannot use apiUrl. because it's let
}
}