3

我有一个功能:

    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

4

1 回答 1

4

首先,您需要确保您的状态已设置,然后您可以通过将上下文状态引用为 来访问它this.state.commits

您需要确保您指的是正确的上下文。

在函数中使用它作为

getTodaysCommits: function(){

    var commits = this.state.commits;
    console.log(commits);

}
于 2016-10-13T10:34:51.057 回答