在反应中访问状态

时间:2016-10-13 10:23:45

标签: javascript html reactjs state setstate

我有一个功能:

    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

1 个答案:

答案 0 :(得分:2)

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

您需要确保引用正确的上下文。

功能中使用它
getTodaysCommits: function(){

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

}