iT邦幫忙

2022 iThome 鐵人賽

DAY 4
0
Software Development

.NET Core與React組合開發技系列 第 4

.NET Core與React組合開發技_第04天_React狀態(State)Stateless跟Stateful比較

  • 分享至 

  • xImage
  •  

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上另一個則是完全沒更新

https://ithelp.ithome.com.tw/upload/images/20220915/20107452l8Knvda9OU.png

https://w2emsx.csb.app/


上一篇
.NET Core與React組合開發技_第03天_增加產品詳細頁元件
下一篇
.NET Core與React組合開發技_第05天_產品清單連結至詳細頁
系列文
.NET Core與React組合開發技30
圖片
  直播研討會
圖片
{{ item.channelVendor }} {{ item.webinarstarted }} |
{{ formatDate(item.duration) }}
直播中

尚未有邦友留言

立即登入留言