admin管理员组文章数量:1305999
I have a function:
getCommits: function() {
fetch('/mits').then((response) => {
if (response.status >= 400) {
throw new Error("Bad response from server");
}
return response.json();
})
.then((mits) => {
this.setState({mits: mits});
});
},
I set the state in this function and now I want other functions to access this state. How can I do this?
this.statemits
was one idea I had.
getTodaysCommits: function(){
fetch('/mits').then((response) => {
if (response.status >= 400) {
throw new Error("Bad response from server");
}
return response.json();
})
.then((mits) => {
var todaysCommits = [];
for (var i = 0; i < mits.length; i++) {
var today = new Date().toDateString();
var stringToDate = new Date(mits[i]mit.author.date).toDateString();
if (today == stringToDate){
todaysCommits.push(mits[i])
}
}
return todaysCommits;
})
.then((todaysCommits) => {
this.setState({mits: todaysCommits});
})
},
In this function how can I use mits without having to fetch it from api and just use the state set in the previous function?
ponentDidMount: function() {
this.getCommits();}
I have my function that gets set on ponentDidMount
I have a function:
getCommits: function() {
fetch('/mits').then((response) => {
if (response.status >= 400) {
throw new Error("Bad response from server");
}
return response.json();
})
.then((mits) => {
this.setState({mits: mits});
});
},
I set the state in this function and now I want other functions to access this state. How can I do this?
this.state.mits
was one idea I had.
getTodaysCommits: function(){
fetch('/mits').then((response) => {
if (response.status >= 400) {
throw new Error("Bad response from server");
}
return response.json();
})
.then((mits) => {
var todaysCommits = [];
for (var i = 0; i < mits.length; i++) {
var today = new Date().toDateString();
var stringToDate = new Date(mits[i].mit.author.date).toDateString();
if (today == stringToDate){
todaysCommits.push(mits[i])
}
}
return todaysCommits;
})
.then((todaysCommits) => {
this.setState({mits: todaysCommits});
})
},
In this function how can I use mits without having to fetch it from api and just use the state set in the previous function?
ponentDidMount: function() {
this.getCommits();}
I have my function that gets set on ponentDidMount
1 Answer
Reset to default 4First you need to make sure that your state is set and then you can access it by referring to the context state as this.state.mits
.
You need to make sure you are referring to the correct context.
Use it in the function as
getTodaysCommits: function(){
var mits = this.state.mits;
console.log(mits);
}
本文标签: javascriptAccessing state in reactStack Overflow
版权声明:本文标题:javascript - Accessing state in react - Stack Overflow 内容由网友自发贡献,该文观点仅代表作者本人, 转载请联系作者并注明出处:http://www.betaflare.com/web/1741813220a2398920.html, 本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,一经查实,本站将立刻删除。
发表评论