Skip to content

Instantly share code, notes, and snippets.

@kuredev
Created August 7, 2020 11:30
Show Gist options
  • Save kuredev/87d62034fbc14fe818a4cb7a53afb0d1 to your computer and use it in GitHub Desktop.
Save kuredev/87d62034fbc14fe818a4cb7a53afb0d1 to your computer and use it in GitHub Desktop.
React Component(クラス)でStateを更新するサンプルコード
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8" />
<title>Fibonacci</title>
<script src="https://unpkg.com/react@16/umd/react.development.js"></script>
<script src="https://unpkg.com/react-dom@16/umd/react-dom.development.js"></script>
<script src="https://unpkg.com/[email protected]/babel.js"></script>
</head>
<body>
<div id="root">wait...</div>
<script type="text/babel">
// State をクリックで更新する
class Fibonacci extends React.Component {
constructor(props){
super(props);
this.state = {
msg: "Fibonacci"
};
this.calcNext = this.calcNext.bind(this);
}
// これでも動く
// calcNext(e){
// this.setState({
// msg: "hoge"
// });
// }
//これでも動く
// updatedMsg = function(){
// return { msg: "hoge" }
// }
// calcNext(e){
// this.setState(
// this.updatedMsg
// )
// }
// 動く (アロー関数Version)
// calcNext(e){
// this.setState(
// () => {
// return { msg: "hoge" }
// }
// )
// }
// 動く (アロー関数+引数にstateを取って前のやつを更新していく)
calcNext(e){
this.setState(
(state) => {
return { msg: state.msg + "Fibonacci" }
}
)
}
render(){
return <div>
<p>{this.state.msg}</p>
<button onClick={this.calcNext}>Calc</button>
</div>;
}
}
ReactDOM.render(<Fibonacci />, document.getElementById('root'));
</script>
</body>
</html>
@kuredev
Copy link
Author

kuredev commented Aug 7, 2020

動かすと↓な感じ。

chrome-capture

@kuredev
Copy link
Author

kuredev commented Aug 7, 2020

参考サイト

【JavaScript】アロー関数とか即時関数とかの書き方メモ https://gist.github.com/kuredev/86108045b1ca51f26ee5479ee4d739ab

React の setState() の引数が関数の場合とオブジェクトの場合の違いについて整理する - Qiita https://qiita.com/im36-123/items/857c96ff60024c0d8a1c

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment