我正在编写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"));
});
答案 0 :(得分:2)
要确保this
引用回调中的组件类,请使用=>
:
$.get "home/users/#{card_name}", (newuser) => @setState names:@state.names.concat([newuser])
^
否则,在执行回调时它超出范围。
答案 1 :(得分:0)
您的$.get
回调没有您的React组件,因为它是this
(或@
)上下文。您可以使用胖箭头=>
来保留@
:
_getSpecificCard: (card_name) ->
$.get "home/users/#{card_name}", (newuser) => self.setState names:self.state.names.concat([newuser])
您可能还需要在将函数传递给子组件时绑定该函数,以确保正确this
:
<SimpleForm addCard={@_getSpecificCard.bind(@)} />