【发布时间】:2017-05-17 11:18:16
【问题描述】:
class App extends Component {
constructor(props){
super(props);
this.state = {
histories: [
{
"name": "Test1",
"date":"25/05/2017",
"question": "Are you happy, today?",
"answer":"Yes"
},
{
"name": "Test2",
"date":"25/05/2017",
"question": "Are you happy, today?",
"answer": "Yes"
}
] };
$.ajax({
url: "http://localhost:xxxx/api/Surveys",
success: (data) => {
this.setState({surveys: data});
},
error: function(xhr,status,err){
console.log('error');
}
});
}
onFormSubmit(id) {
console.log("Started");
fetch("http://localhost:xxxx/api/Surveys/" + id + "/submit", {
method:'POST'
})
.then(function(response){
if(response.ok) {
console.log('success');
//this is not defined here
this.setState({
histories: [
{
"name": "Test3",
"date":"25/05/2017",
"question": "Are you happy, today?",
"answer":"Yes"
},
{
"name": "Test4",
"date":"25/05/2017",
"question": "Are you happy, today?",
"answer": "Yes"
}
]
})
}
else {
console.log('error');
}
})
.catch(function(error){
console.log('catch error');
});
}
render(){
return (
<div>
<History
Histories={this.state.histories} />
</div>
);
}
}
嗨,我是新手,我已经在构造函数中声明了历史记录,我试图在回调时在 web 服务中设置历史记录状态,调试时这是未定义的。
这是在<History Histories={this.state.histories} /> 中定义的,但它在回调中是未定义的,请问有人可以帮我吗?我已经搜索过,有人推荐使用 ref,但是 ref 怎么能与这种状态连接呢?如果有人举个例子,我将不胜感激。
【问题讨论】:
标签: javascript reactjs react-redux babeljs