Versions Compared

Key

  • This line was added.
  • This line was removed.
  • Formatting was changed.

...

Code Block
languagejs
import React from 'react';

class App extends React.Component {
   constructor(props) {
      super(props);

      this.state = {
         header: "Header from state...",
         content: "Content from state..."
      }
   }
   render() {
      return (
         <div>
            <h1>{this.state.header}</h1>
            <h2>{this.state.content}</h2>
         </div>
      );
   }
}
export default App;

index.js:

Code Block
import React from 'react';
import ReactDOM from 'react-dom';
import App from './App.js';

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

Và ta được kết quả là:

...

Set State

setState() là method để cập nhật giá trị của state trong component. Nó sẽ không xóa bỏ đi state mà chỉ là thay đổi giá trị của nó.

Update app.js

Code Block
import React from 'react';

class App extends React.Component {
   constructor() {
      super();
		
      this.state = {
         data: []
      }
	
      this.setStateHandler = this.setStateHandler.bind(this);
   };
   setStateHandler() {
      var item = "setState..."
      var myArray = this.state.data.slice();
	  myArray.push(item);
      this.setState({data: myArray})
   };
   render() {
      return (
         <div>
            <button onClick = {this.setStateHandler}>SET STATE</button>
            <h4>State Array: {this.state.data}</h4>
         </div>
      );
   }
}
export default App;

Ban đầu giá trị của data là một mảng rỗng. Mối lần người dùng click vào button, giá trị của data sẽ được thêm vào giá trị mới setState.... Nếu chúng ta click 3 lần giá trị của data sẽ là: data = ["setState...", "setState...", "setState..."].

Props:

Trong ReactJs ngoài state ra còn 1 hình thức lưu giữ data nữa đó là props, vậy props khác state như thế nào? Hiểu đơn giản là state thuộc về component, bạn có thể update, chỉnh sửa state, còn props cũng lưu dữ liệu như state nhưng được nhận từ component cha truyền xuống, bạn không thể chỉnh sửa trực tiếp props mà phải thay đổi từ cha nó. Bạn xem ví dụ sau để hiểu rõ hơn:

...