ReactとNodejsを使用した非常にシンプルなカウンターアプリケーション。クライアント側には、カウント状態とデフォルト値0のUIでのレンダリングで構成されるカウンターコンポーネントがあり、ユーザーがインクリメントボタンを押すたびに、ノードサーバーへのPOSTリクエストAPIがトリガーされます。次に、ノードサーバーは要求を処理し、その結果でクライアントに応答します。どうすればこれを達成できますか?
クライアント側(カウンターコンポーネント)
this.state = {
count : 0
}
sendAPI() {
axios.post('http://localhost:3001/increment', this.state.count)...
}
render() {
<div>
<button onClick = {this.sendAPI()} type="button">increment</button>
Counter: {this.state.count}
</div>
}
サーバー側(エクスプレスサーバー)
app.post('/increment', function(req,res) {
res.send(req.body.count + 1)
}
クライアント側でres.send()データを「this.state.count」に戻すにはどうすればよいですか?
ボタンでonClick
は、関数を呼び出さずに、参照として関数を渡します。
state = {
count : 0
}
sendAPI() {
axios.post('http://localhost:3001/increment', {count: this.state.count})
.then(res => {
const count = res.data;
this.setState({count: +count})
);
}
render() {
<div>
<button onClick = {this.sendAPI} type="button">increment</button>
Counter: {this.state.count}
</div>
}
サーバー側(エクスプレスサーバー)
app.post('/increment', function(req,res) {
res.send(+req.body.count + 1)
}
この記事はインターネットから収集されたものであり、転載の際にはソースを示してください。
侵害の場合は、連絡してください[email protected]
コメントを追加