【发布时间】:2021-02-02 17:55:59
【问题描述】:
我正在尝试让 API 提取一个单词并将其设置为状态。然后一个函数将读取该状态并完成其设计目的。然而,我最初编码它的方式称它是乱序的。第三个代码 sn -p 可以让代码成功运行,但我不知道为什么。有人能解释一下有什么区别或为什么原来的方法不起作用吗?
下面是API函数,后面是第二个函数。
wordNikApi = () => {
fetch("http://api.wordnik.com:80/v4/words.json/randomWords?hasDictionaryDef=true&minCorpusCount=0&minLength=5&maxLength=15&limit=1&api_key=/* Removed */")
.then( res => res.json() )
.then( ( result ) => {
this.setState({
apiWord: result[0].word,
});
console.log("wordNikApi: ", this.state.apiWord);
})
.catch( ( error ) => {
console.log("API ERROR: ", error);
})
};
resetGame = () => {
console.log("resetGame");
this.wordNikApi();
this.setState({
word: [],
count: 0,
allAttempts: [],
letterIndex: [],
numberOfBadAttempts: 0,
remainingAttempts: 6,
repeat: false,
pageLock: false,
invalidKey: false,
}, () => {
console.log("resetGame: function 1");
console.log(this.state.apiWord);
let fullWord = "word";
let wordArray = fullWord.split("");
let wordLength = wordArray.length;
// Send wordObj to state with value and index
let wordObj = wordArray.map((value, index) => {
return {
found: false,
val: value,
id: index,
}
})
this.setState({
word: wordObj,
wordLength: wordLength,
remainingAttempts: 6,
});
});
};
功能代码:
resetGame = () => {
console.log("resetGame");
// this.wordNikApi();
fetch("http://api.wordnik.com:80/v4/words.json/randomWords?hasDictionaryDef=true&minCorpusCount=0&minLength=5&maxLength=15&limit=1&api_key=/* Removed */")
.then( res => res.json() )
.then( ( result ) => {
this.setState({
apiWord: result[0].word,
}, ()=> {
let fullWord = this.state.apiWord;
let wordArray = fullWord.split("");
let wordLength = wordArray.length;
// Send wordObj to state with value and index
let wordObj = wordArray.map((value, index) => {
return {
found: false,
val: value,
id: index,
}
})
this.setState({
word: wordObj,
wordLength: wordLength,
remainingAttempts: 6,
count: 0,
allAttempts: [],
letterIndex: [],
numberOfBadAttempts: 0,
repeat: false,
pageLock: false,
invalidKey: false,
});
});
})
.catch( ( error ) => {
console.log("API ERROR: ", error);
})
};
【问题讨论】:
标签: javascript reactjs api fetch