ReactJS(2)Components State and Lifecycle

ReactJS(2)Components State and Lifecycle

ENV
>node --version && npm --version
v8.0.0
5.0.0

Extracting Components
It is great idea to split the components.

function formatDate(date) {
  return date.toLocaleDateString();
}

function Avatar(props) {
  return (
    <img className="Avatar"
         src={props.user.avatarUrl}
         alt={props.user.name} />
  );
}

function UserInfo(props) {
  return (
    <div className="UserInfo">
      <Avatar user={props.user} />
      <div className="UserInfo-name">
        {props.user.name}
      </div>
    </div>
  );
}

function Comment(props) {
  return (
    <div className="Comment">
      <UserInfo user={props.author} />
      <div className="Comment-text">
        {props.text}
      </div>
      <div className="Comment-date">
        {formatDate(props.date)}
      </div>
    </div>
  );
}

const comment = {
  date: new Date(),
  text: 'I hope you enjoy learning React!',
  author: {
    name: 'Hello Kitty',
    avatarUrl: 'http://placekitten.com/g/64/64' };
  }

ReactDOM.render(
  <Comment
    date={comment.date}
    text={comment.text}
    author={comment.author} />,
  document.getElementById('root')
);

Props are Read-Only
All React components must act like pure functions with respect to their props.

State and Lifecycle
State is similar to props, it is private and fully controlled by the component. Local state is exactly a feature available only to classes.

Converting a Function to a Class
1 Create an ES6 class with the same name that extends React.Component.
2 Add a single empty method to it called render()
3 Move the body of the function into the render()
4 Replace props to this.props

class Clock extends React.Component {
    render() {
        return (
            <div> … </div>
        )
    }
}

Adding Local State to a Class
1 Replace this.props.date with this.state.date in render()
2 Add a class contractor that assign the initial this.state
3 Remove the date prop from the <Clock /> element

class Clock extends React.Component {
  constructor(props) {
    super(props);
    this.state = {date: new Date()};
  }

  render() {
    return (
      <div>
        <h1>Hello, world!</h1>
        <h2>It is {this.state.date.toLocaleTimeString()}.</h2>
      </div>
    );
  }
}

Adding Lifecycle Methods to a Class
mounting and unmounting in React
The method componentDidMount() hook runs after the component output has been rendered to the DOM.

We render DOM only once, but every time when we call tick(), it will change the state value in render.
class Clock extends React.Component {
  constructor(props) {
    super(props);
    this.state = {date: new Date()};
  }

  componentDidMount() {
    this.timerID = setInterval(
      () => this.tick(),
      1000
    );
  }

  componentWillUnmount() {
    clearInterval(this.timerID);
  }

  tick() {
    this.setState({
      date: new Date()
    });
  }

  render() {
    return (
      <div>
        <h1>Hello, world!</h1>
        <h2>It is {this.state.date.toLocaleTimeString()}.</h2>
      </div>
    );
  }
}

ReactDOM.render(
  <Clock />,
  document.getElementById('root')
);

Using State Correctly
1 Do Not Modify State Directly
this.state.comment = “hello”; //Wrong
this.setState({comment:’Hello'});
     The only place where we can assign this.state is the constructor

2 State Updates May Be Asynchronous
second format of setState method
this.setState(function(prevState, props){
    return {
        counter: prevState.counter + props.increment
    };
});

3 State Updates are Merged
constructor(props) { super(props); this.state = { posts: [], comments: [] }; }
componentDidMount() {
    fetchPosts().then(response => { this.setState({ posts: response.posts }); });
    fetchComments().then(response => { this.setState({ comments: response.comments }); });
}

we can call this.setState multiple times, it will merge itself.

Data Flow
function App() {
    return ( <div> <Clock /> <Clock /> <Clock /> </div> );
}
ReactDOM.render( <App />, document.getElementById('root'));

Each Clock sets up its own timer and updates independently.

References:
https://facebook.github.io/react/docs/components-and-props.html
https://facebook.github.io/react/docs/state-and-lifecycle.html



Guess you like

Origin http://10.200.1.11:23101/article/api/json?id=326629422&siteId=291194637