【问题标题】:Why is my setState not working when passed as an argument to a function?为什么我的 setState 在作为参数传递给函数时不起作用?
【发布时间】:2021-05-29 22:12:48
【问题描述】:

对于函数 fetchApiAndSetStateForWrongGuesses(),我将两个参数分别称为 randNumwrongGuess。 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


【解决方案1】:

在您的回调函数中,wrongGuess 仍然绑定到您传递给函数的参数。 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}`)})
        })

【讨论】:

  • 感谢这工作!你的解释很有道理。所以用我自己的话来解释:基本上回调函数中的 wrongGuess 指向参数中的 wrongGuess(它本身被指向一个在构造函数中初始化的空字符串)。所以即使 setState 更新了,回调函数中的 wrongGuess 仍然“指向”它最初的空字符串。换句话说,setState WAS 更新它只是 console.log 正在查看错误的内容。我希望我做对了。
  • 是的,你明白了。乐于助人!
【解决方案2】:

这可能是因为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}`)})
        })
}

【讨论】:

    【解决方案3】:

    您的初始状态中没有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: "",
            }
    

    【讨论】:

      猜你喜欢
      • 2012-03-27
      • 2015-09-09
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2022-01-23
      • 1970-01-01
      相关资源
      最近更新 更多