‘State’ is a JS object that contains data relevant to a component
Updating ‘state’ on a component causes the component to (almost) instantly rerender
State must be initialized when a component is created
State can only be updated using the function ‘setState’
import React from'react';import ReactDOM from'react-dom';classAppextendsReact.Component{constructor(props){// Super is a reference to the parent's constructor function and allsuper(props);// Initialized// This is the only time we do direct assignment// to this.statethis.state ={ lat:null, errorMessage:''};
window.navigator.geolocation.getCurrentPosition(
position =>{
console.log(position)// We called setState!!this.setState({ lat: position.coords.latitude });// We did not!!!!// this.state.lat = position.coords.latitude},
err =>{
console.log(err)this.setState({ errorMessage: err.message })});}// React says we have to define render!!render(){return(<div>
Latitude:{this.state.lat}<br />
Error:{this.state.errorMessage}</div>);}}
ReactDOM.render(<App />, document.querySelector('#root'))
댓글
댓글 쓰기