【发布时间】:2021-05-29 22:12:48
【问题描述】:
对于函数 fetchApiAndSetStateForWrongGuesses(),我将两个参数分别称为 randNum 和 wrongGuess。 randNum 只是一个数字,但 wrongGuess 应该是一个状态。问题是当我将 wrongGuess 传递给函数 fetchApiAndSetStateForWrongGuesses() 时,setState 不起作用。当它到达 console.log 时,它只会打印出一个空字符串,因为这就是构造函数初始化它的内容。如何获取它以便 setState 根据我传递给它的状态实际工作?
class PokemonGenerator extends Component {
totalPokemon = 151
constructor() {
super()
this.state = {
currentImg: "https://d.newsweek.com/en/full/822411/pikachu-640x360-pokemon-anime.jpg?w=1600&h=1200&q=88&f=3ed1c0d6e3890cbc58be90f05908a8f5",
currentName: "",
wrongChoice1: "",
wrongChoice2: "",
wrongChoice3: "",
}
this.handleClick = this.handleClick.bind(this)
this.handleChange = this.handleChange.bind(this)
}
handleClick(event) {
// event.preventDefault()
const randNum1 = Math.floor(Math.random() * this.totalPokemon)
const randNum2 = Math.floor(Math.random() * this.totalPokemon)
const randNum3 = Math.floor(Math.random() * this.totalPokemon)
const randNum4 = Math.floor(Math.random() * this.totalPokemon)
fetch('https://pokeapi.co/api/v2/pokemon/' + randNum1)
.then(response => response.json())
.then(response => {
this.setState({
currentImg: response['sprites']['front_default'],
currentName: response.name
}, function() {console.log(`CORRECT ANSWER: ${this.state.currentName}`)})
})
this.fetchApiAndSetStateForWrongGuesses(randNum2, this.state.wrongChoice1)
this.fetchApiAndSetStateForWrongGuesses(randNum3, this.state.wrongChoice2)
this.fetchApiAndSetStateForWrongGuesses(randNum4, this.state.wrongChoice3)
}
fetchApiAndSetStateForWrongGuesses(randNum, wrongGuess) {
fetch('https://pokeapi.co/api/v2/pokemon/' + randNum)
.then(response => response.json())
.then(response => {
this.setState({
wrongGuess: response.name
}, function () {console.log(`Wrong Choice: ${wrongGuess}`)})
})
}
【问题讨论】:
-
wrongGuess不是状态值的名称,它是传递给fetchApiAndSetStateForWrongGuesses(randNum, wrongGuess) { ... }函数的第二个参数的名称。我认为你的意思是function () {console.log(Wrong Choice: ${this.state.wrongGuess})})
标签: javascript reactjs react-native state setstate