React 組件具有“狀態”的概念。
在產品列表和產品詳細元件中都可看到有所謂的state
採用 javascript 物件形式,該物件會屬於private的並由該組件自行內部存取控制,
換言之,不能直接從另一個A組件訪問一個B組件的狀態,以讀取或更改它。
這邊
https://codesandbox.io/s/new
用線上沙盒測試demo
分別去建立
Stateless和Stateful的 Component
stateful.js
import React, { Component } from "react";
//have access to props and state
class CounterComponent extends Component {
count = 0;
constructor() {
super();
this.state = {
counter: 0
};
}
handleClick = () => {
this.setState({
counter: this.state.counter + 1
});
};
render() {
return (
<div>
<p>Counter : {this.state.counter}</p>
<button onClick={this.handleClick}>Click</button>
</div>
);
}
}
export default CounterComponent;
stateless.js
import React from "react";
const course = {
name: "React",
message: "Welcome react stateless!"
};
//Doesn't have access to state
const CourseComponent = () => {
let counter = 0;
let handleClick = () => {
//updating variable value
//but not reflecting because of stateless nature
counter = counter + 1;
alert(counter);
};
return (
<div>
<h3>{course.name}</h3>
<p>{course.message}</p>
<p>Counter : {counter}</p>
<button onClick={handleClick}>Click</button>
</div>
);
};
export default CourseComponent;
App.js
import React from "react";
import "./styles.css";
import CounterComponent from "./stateful";
import CourseComponent from "./stateless";
const App = () => {
return (
<>
<h2>Stateless Componnet</h2>
<CourseComponent />
<h2>Stateful Componnet</h2>
<CounterComponent />
</>
);
};
export default App;
可觀察到
一個有遞增顯示在UI上另一個則是完全沒更新