差異處
這裏顯示兩個版本的差異處。
Both sides previous revision 前次修改 下次修改 | 前次修改 | ||
web:reactjs:react_hook:usestate [2019/02/22 21:48] tony |
web:reactjs:react_hook:usestate [2023/06/25 09:48] (目前版本) |
||
---|---|---|---|
行 1: | 行 1: | ||
+ | {{tag>reactjs}} | ||
====== React Hook - useState ====== | ====== React Hook - useState ====== | ||
===== Introduction ===== | ===== Introduction ===== | ||
- | 在我研究React到現在,我認為React是基於state去決定UI該怎麼呈現。而在2018年React提出了Hook,賦予了Function Component擁有了React State的概念。我以大家最常使用的Counter範例,來分享用法。一個Counter UI,它透過div顯示次數,透過點擊button去增加次數;在使用React Component的寫法時,程式碼如下,你必須透過this.state宣告member,而透過setState告知React狀態的改變: | + | 從我研究React到現在,我認為React是基於state去決定UI該怎麼呈現。在2018年React提出了Hook,賦予了Function Component擁有了React State的概念。我以大家最常使用的Counter範例,來分享用法。一個Counter UI,它透過div顯示次數,透過點擊button去增加次數;在使用React Component的寫法時,程式碼如下,你必須透過this.state宣告member,而透過setState告知React狀態的改變: |
<code javascript> | <code javascript> | ||
import React, { Component } from "react" | import React, { Component } from "react" | ||
行 53: | 行 54: | ||
}); | }); | ||
</code> | </code> | ||
- | 但我發現click並無法觸發狀態的改變。爬一下文,發現這目前是enzyme的問題,也許以後某天會改。因此我改用react-testing-library做測試: | + | 但我發現click並無法觸發狀態的改變。爬一下文,發現這目前是enzyme的問題[[https://github.com/reactjs/rfcs/issues/71|link]],也許以後某天會改。因此我改用react-testing-library做測試: |
<code javascript> | <code javascript> | ||
import CounterFunc from "../CounterFunc"; | import CounterFunc from "../CounterFunc"; | ||
行 88: | 行 89: | ||
</code> | </code> | ||
===== Reference ===== | ===== Reference ===== | ||
- | * [[https://reactjs.org/docs/hooks-state.html|hooks state]] | + | * [[https://reactjs.org/docs/hooks-state.html|reactjs - hooks state]] |
+ | * [[https://jestjs.io/docs/en/getting-started|jest - getting-started]] | ||
+ | ===== ===== | ||
+ | ---- | ||
+ | \\ | ||
+ | ~~DISQUS~~ |