繁体   English   中英

为什么我的 setState 在作为参数传递给 function 时不起作用?

[英]Why is my setState not working when passed as an argument to a function?

对于 function fetchApiAndSetStateForWrongGuesses()我传递了两个参数,称为randNumwrongGuess randNum 只是一个数字,但wrongGuess应该是 state。 问题是当我将wrongGuess传递给 function fetchApiAndSetStateForWrongGuesses()时,setState 不起作用。 当它到达 console.log 时,它只会打印出一个空字符串,因为这就是构造函数初始化它的内容。 我怎样才能得到它,以便 setState 根据我传递给它的 state 实际工作?

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}`)})
        })
}

在您的回调 function 中, wrongGuess仍然绑定到您传递给 function 的参数。 setState更新this.state ,因此您需要从那里访问新值。

    fetch('https://pokeapi.co/api/v2/pokemon/' + randNum)
        .then(response => response.json())
        .then(response => {
            this.setState({
                wrongGuess: response.name
            }, function () {console.log(`Wrong Choice: ${this.state.wrongGuess}`)})
        })

这可能是因为this存在的上下文。 尝试这样做:

fetchApiAndSetStateForWrongGuesses(randNum, wrongGuess) {
    const self = this
    fetch('https://pokeapi.co/api/v2/pokemon/' + randNum)
        .then(response => response.json())
        .then(response => {
            self.setState({
                wrongGuess: response.name
            }, function () {console.log(`Wrong Choice: ${wrongGuess}`)})
        })
}

您在初始状态下没有错猜wrongGuess

 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: "",
        }

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM