Masalah dengan Permintaan POST di React
Klik tombol berfungsi, karena saya dapat melihat log tetapi permintaan POST tidak terjadi. Saya telah membuat kotak input sederhana, dan ketika tombol diklik, itu akan mengirim permintaan POST ke server.
Saya tidak tahu mengapa permintaan POST tidak pernah terjadi, jadi tolong bantu saya mengetahuinya.
Comment.js:
import React from 'react';
export class Comment extends React.Component {
constructor(props){
super(props);
this.handleClick = this.handleClick.bind(this);
}
handleClick() {
//SEND POST request
console.log('handling click');
const xhr = new XMLHttpRequest();
const URL = "http://localhost:8080/api/comments"
xhr.onreadystatechange = () => {
if(xhr.readyState === XMLHttpRequest.DONE){
console.log('POST request sent, comment posted.')
}
xhr.open('POST',URL);
xhr.setRequestHeader('Content-type', 'text/plain');
xhr.send(document.getElementById('comment-box').value);
}
}
render(){
const comment_form = (
<div className="posts">
<input type="text" id="comment-box" name="comment" placeholder="Say something nice." />
<button className="submit-button" type="button" onClick={this.handleClick}> Comment </button>
</div>
);
return comment_form;
}
}
Jawaban
Anda mengalami kesalahan sintaksis seperti penutupan} dari eventhandler onReadyState tidak tepat
import React from "react";
import "./styles.css";
export class Comment extends React.Component {
constructor(props) {
super(props);
this.handleClick = this.handleClick.bind(this);
}
handleClick() {
//SEND POST request
console.log("handling click");
const xhr = new XMLHttpRequest();
const URL = "http://localhost:8080/api/comments";
xhr.onreadystatechange = () => {
if (xhr.readyState === XMLHttpRequest.DONE) {
console.log("POST request sent, comment posted.");
}
};
xhr.open("POST", URL);
xhr.setRequestHeader("Content-type", "text/plain");
console.log(document.getElementById("comment-box").value);
xhr.send(document.getElementById("comment-box").value);
}
render() {
const comment_form = ( <
div className = "posts" >
<
input type = "text"
id = "comment-box"
name = "comment"
placeholder = "Say something nice." /
>
<
button className = "submit-button"
type = "button"
onClick = {
this.handleClick
} >
{
" "
}
Comment {
" "
} <
/button> <
/div>
);
return comment_form;
}
}
Menjawab
Fungsi panah mengikat this
dan callback onreadystatechange dipanggil saat this === Comment
. Jadi xhr.onreadystatechange tidak berfungsi.
xhr.onreadystatechange = function() {
if(xhr.readyState === XMLHttpRequest.DONE){
console.log('POST request sent, comment posted.')
}
Saya pikir referensi di bawah ini sangat membantu Anda. Bukan masalah dari reaksi melainkan dari fungsi panah.
Referensi ini lebih jelas menulis tentang masalah itu.
Referensi
- Javascript sintaks lama untuk konversi fungsi panah