我有以下测试代码
<body>
<div id="content"></div>
<script type="text/jsx">
var InputText = React.createClass({
handleSubmit: function (query) {
var q = document.getElementById("qval").value;
console.dir("Query submitted " + q);
$.ajax({
url: "http://localhost:8080/hello",
datatype: 'json',
cache: false,
method: 'POST',
success: function (data) {
this.setState({data: data});
}.bind(this),
error: function (xhr, status, err) {
alert("error" + status + " dd " + err.toString());
console.error(status, err.toString());
}
});
},
getInitialState: function() {
return{data: "ask a question"};
},
render: function() {
const val = this.state.data;
console.log("data is " + val);
return (
<div>
<form className="inputText" onSubmit ={this.handleSubmit}>
<input type="text" id="qval" value = "" placeholder="ask a question"/>
<input type="submit" value="Submit" />
</form>
{this.state.data}
</div>
);
}
});
var element = React.createElement(InputText);
React.render(element,document.getElementById("content"));
</script>
</body>
我发现在执行ajax调用之后,在渲染函数val中打印来自服务器的响应,然后输出默认值(问一个问题)。看起来因为某种原因再次调用getInitialState。那是为什么?