我有一个功能:
getCommits: function() {
fetch('/commits').then((response) => {
if (response.status >= 400) {
throw new Error("Bad response from server");
}
return response.json();
})
.then((commits) => {
this.setState({commits: commits});
});
},
我在此函数中设置状态,现在我希望其他函数访问此状态。我怎么能这样做?
this.state.commits
是我的一个想法。
getTodaysCommits: function(){
fetch('/commits').then((response) => {
if (response.status >= 400) {
throw new Error("Bad response from server");
}
return response.json();
})
.then((commits) => {
var todaysCommits = [];
for (var i = 0; i < commits.length; i++) {
var today = new Date().toDateString();
var stringToDate = new Date(commits[i].commit.author.date).toDateString();
if (today == stringToDate){
todaysCommits.push(commits[i])
}
}
return todaysCommits;
})
.then((todaysCommits) => {
this.setState({commits: todaysCommits});
})
},
在这个函数中,如何在不必从api中获取提交的情况下使用提交,只使用上一个函数中设置的状态?
componentDidMount: function() {
this.getCommits();}
我的功能设置在componentDidMount
答案 0 :(得分:2)
首先,您需要确保您的状态已设置,然后您可以通过将上下文状态称为this.state.commits
来访问它。
您需要确保引用正确的上下文。
在
功能中使用它getTodaysCommits: function(){
var commits = this.state.commits;
console.log(commits);
}