【问题标题】:Accessing state in react在反应中访问状态
【发布时间】:2017-02-22 10:07:34
【问题描述】:

我有一个函数:

    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

【问题讨论】:

    标签: javascript html reactjs state setstate


    【解决方案1】:

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

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

    在函数中使用它

    getTodaysCommits: function(){
    
        var commits = this.state.commits;
        console.log(commits);
    
    }
    

    【讨论】:

    • 那会在第二个函数中的什么位置呢?然后我怎么打电话给.then呢?
    • 你不需要再次获取它,只需使用这个状态变量。
    • 好吧,有道理,最后一个问题。我已更新以显示我的全部 getTodaysCommits()。我想摆脱所有 fetch 部分并将其替换为 var commits = this.state.commits; 但这意味着我不能为此调用我的 .then 承诺?
    • 无论你在 then 调用中拥有什么,你都可以在没有它的情况下访问它。这不是问题
    猜你喜欢
    • 1970-01-01
    • 2018-11-13
    • 2021-02-23
    • 1970-01-01
    • 2017-01-30
    • 2020-12-17
    • 1970-01-01
    • 2021-09-29
    • 1970-01-01
    相关资源
    最近更新 更多