这是我的第一个 React 代码。我正在尝试从 React 调用 Restful Web 服务。 它一直说“未捕获的类型错误:this.setState 不是一个函数”。我无法弄清楚代码有什么问题。
<!DOCTYPE html>
<html>
<head>
<title>React Flux</title>
<script src="https://fb.me/react-0.13.3.js"></script>
<script src="https://fb.me/JSXTransformer-0.13.3.js"></script>
<script src="http://code.jquery.com/jquery-2.1.4.min.js"></script>
</head>
<body>
<div id="component"></div>
<script type="text/jsx">
var JavaEEWSTest = React.createClass({
getInitialState: function () {
return {text: ''};
},
componentDidMount: function(){
$.ajax({
url: "http://localhost:8080/rest/user/456"
}).then(function(data) {
this.setState({text: data.name});
}).bind(this)
},
render: function() {
return <div>Response - {this.state.text}</div>;
}
});
React.render(<JavaEEWSTest />, document.getElementById('component'));
</script>
</body>
</html>
最佳答案
你需要设置this
为回调函数
$.ajax({
url: "http://localhost:8080/rest/user/456"
}).then(function(data) {
this.setState({text: data.name});
}.bind(this))
^^^^^^^^^^^
但不适用于 $.ajax/then
- }).bind(this)
关于javascript - React Uncaught TypeError : this. setState 不是函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34839406/