React ve ES6'yı öğrenme yolunda, resmi eğitimi aldım ve ES6'yı uyumlu hale getirmek için etrafta dolaştım. İşte Neden this.props ReactJS kodumda tanımsız?
benim CommentBox dosya/kod edilir: Ajax talebin yerine gelince, aşağıdaki hatayı alıyorumCommentBox.js:23 Uncaught TypeError: Cannot read property 'url' of undefined
import React from 'react';
import CommentList from './CommentList.js';
import CommentForm from './CommentForm.js';
export default class CommentBox extends React.Component {
constructor(props) {
super(props);
console.log(this.props)
this.state = {
data: []
}
}
loadCommentsFromServer() {
$.ajax({
url: this.props.url,
dataType: 'json',
cache: false,
success: function(data) {
this.setState({data: data});
}.bind(this),
error: function(xhr, status, err) {
console.error(this.props.url, status, err.toString());
}.bind(this)
});
}
handleCommentSubmit(comment) {
let comments = this.state.data;
// Optimistically set id on the new comment.
// It will be replaced by an id generated by the server.
// In a production you would have a more robust system in place.
comment.id = Date.now();
let newComments = comments.concat([comment]);
this.setState({data: newComments});
$.ajax({
url: this.props.url,
dataType: 'json',
type: 'POST',
data: comment,
success: function(data) {
this.setState({data: data});
}.bind(this),
error: function(xhr, status, err) {
this.setState({data: comments});
console.error(this.props.url, status, err.toString());
}.bind(this)
});
}
componentDidMount() {
this.loadCommentsFromServer();
setInterval(this.loadCommentsFromServer, this.props.pollInterval);
}
render() {
return (
<div className="commentBox">
<h1>Comments</h1>
<CommentList data={this.state.data} />
<CommentForm onCommentSubmit={this.handleCommentSubmit} />
</div>
);
}
}
hata
loadCommentsFromServer
üzerinde gerçekleşmesi
; this.props
'un ne olduğunu bilmiyor gibi görünüyor. Bu referansınnumaralı bir sorun olduğunu düşündüm ve sorunu çözmek için yeni ES6 okları kullanması önerildiği similar question bulundu. Daha sonra denedim: loadCommentsFromServer =() => {}
, ancak Browserify şikayet ediyor ve oluşturmuyor.
Olası yinelenen [Doğru \ 'this \'/bağlamda bir geri arama içine nasıl erişilir?] (Http://stackoverflow.com/questions/20279484/how-to-access-the-correct-this-context -ide-geri arama) –
Önerilen yinede "Ortak sorun: nesne yöntemlerini geri arama/olay işleyicileri olarak kullanma" konusuna bakın. –
El ile bağlamanız gerekir. ES6 sınıfı – thangngoc89