我在寫reactjs(coffescript + JSX語法)。如果用戶寫了一些內容的輸入,然後點擊按鈕,獲得AJAX請求被髮送,結果在回調函數(JSON對象)沒有插入的狀態下使用的setState 名,我得到以下錯誤:無法讀取屬性未定義無法讀取反應中未定義的屬性「名稱」
「名字」,我不知道應該是一個問題
$ ->
# first component
MainComponent = React.createClass
getInitialState: ->
names:[]
_getSpecificCard: (card_name) ->
$.get "home/users/#{card_name}", (newuser) -> @setState names:@state.names.concat([newuser])
_getAllcards: ->
@state.names.map((user) ->
<Card key={user.id} name={user.login} avatarurl={user.avatar_url} />)
render: ->
cards= @_getAllcards
<div>
<SimpleForm addCard={@_getSpecificCard} />
{cards}
</div>
# second component
SimpleForm= React.createClass
_handleSubmit: (e) ->
e.preventDefault()
textInput= @refs.login
@props.addCard(textInput.value)
render: ->
<form onSubmit={@_handleSubmit}>
<input placeholder="github login" ref="login" />
<button>Show user</button>
</form>
# third component
Card = React.createClass
render: ->
<div>
<h3>{@props.name}</h3>
<img src={@props.avatarurl} width=80 />
</div>
ReactDOM.render(<MainComponent />,document.getElementById("pluralsight"))
//編譯版本
$(function() {
var Card, MainComponent, SimpleForm;
MainComponent = React.createClass({displayName: "MainComponent",
getInitialState: function() {
return {
names: []
};
},
_getSpecificCard: function(card_name) {
return $.get("home/users/" + card_name, function(newuser) {
return this.setState({
names: this.state.names.concat([newuser])
});
});
},
_getAllcards: function() {
return this.state.names.map(function(user) {
return React.createElement(Card, {
"key": user.id,
"name": user.login,
"avatarurl": user.avatar_url
});
});
},
render: function() {
var cards;
cards = this._getAllcards;
return React.createElement("div", null, React.createElement(SimpleForm, {
"addCard": this._getSpecificCard
}), cards);
}
});
SimpleForm = React.createClass({displayName: "SimpleForm",
_handleSubmit: function(e) {
var textInput;
e.preventDefault();
textInput = this.refs.login;
return this.props.addCard(textInput.value);
},
render: function() {
return React.createElement("form", {
"onSubmit": this._handleSubmit
}, React.createElement("input", {
"placeholder": "github login",
"ref": "login"
}), React.createElement("button", null, "Show user"));
}
});
Card = React.createClass({displayName: "Card",
render: function() {
return React.createElement("div", null, React.createElement("h3", null, this.props.name), React.createElement("img", {
"src": this.props.avatarurl,
"width": 80
}));
}
});
return ReactDOM.render(React.createElement(MainComponent, null), document.getElementById("pluralsight"));
});
你有可能提供預處理版本的代碼嗎?這會讓我們對CoffeeScript幫助不太熟悉。 – Yoric