猿问

React应用未对预期的变化做出反应。为什么?

乡亲。我可能有一个新手问题,不过我还是会射击。下面的代码段非常简单,我不应该遇到问题,但是我们开始吧。我正在尝试获取ColorsGrid组件中的颜色列表。简而言之,当用户通过下拉列表更改难度级别时,应生成一组新的颜色并进行显示。我认为这是一个非常简单的练习,但是事情并没有按预期进行。每当我改变难度时,它都不会做出反应(渲染ColorsGrid组件),只有在我再次选择另一个(难度)级别之后,上一个级别才会引发重新渲染。例如,如果我要在初始渲染后选择“中”(默认级别设置为“简单”),则没有任何变化。但是,如果我回到“轻松”(或选择其他任何难度),那么是否会发生与前一个(中等难度)相对应的更改,即ColorsGrid重新渲染,因此显示了与中等难度相对应的网格。我究竟做错了什么?


以下是相关代码。


import React, { Component } from 'react';

import ReactDOM from 'react-dom';


// Get random rgb color

function randomColor() {

  let r = Math.floor(Math.random() * 256);

  let g = Math.floor(Math.random() * 256);

  let b = Math.floor(Math.random() * 256);


  return `rgb(${r}, ${g}, ${b})`;

}


// Set length of color list array as a funciton of difficulty 

function colorsListLength(difficulty) {

  switch (true) {

    case difficulty === 'expert':

      return 25;

    case difficulty === 'hard':

      return 20;

    case difficulty === 'medium':

      return 10;

    default:

      return 5;

  }

}


// Get color list array

function colorsList(colorsLength = 5) {

  const colors = [];


  while (colors.length < colorsLength) {

    colors.push(randomColor());

  }


  return colors;

}


// Set random color to guess from (above) color list array

function randomColorToGuess(colors) {

  const index = Math.floor(Math.random() * colors.length);


  return colors[index];

}


// Set number of game tries as a function of difficulty

function numberOfTries(difficulty) {

  switch (true) {

    case difficulty === 'expert' || difficulty == 'hard':

      return 2;

    case difficulty === 'medium':

      return 1;

    default:

      return 0;

  }

}


弑天下
浏览 152回答 2
2回答

慕容3067478

这是因为setState()是异步:setState(newState,回调);为了获得刚刚选择的难度,您必须像这样更改代码:this.setState({&nbsp; difficulty: e.target.value,&nbsp;}, () => this.colorsArray(this.state.difficulty));

繁星淼淼

问题在于您对setState的调用是否协调。以下是cleas的事情:&nbsp; colorsArray(difficulty) {&nbsp; &nbsp; const colors = colorsList(colorsListLength(difficulty));&nbsp; &nbsp; const colorToGuess = randomColorToGuess(colors);&nbsp; &nbsp; this.setState(() => ({&nbsp; &nbsp; &nbsp; difficulty,&nbsp; &nbsp; &nbsp; colorsList: colors,&nbsp; &nbsp; &nbsp; gameTries: numberOfTries(this.state.difficulty),&nbsp; &nbsp; &nbsp; colorToGuess&nbsp; &nbsp; }));&nbsp; }&nbsp; handleChange(e) {&nbsp; &nbsp; this.colorsArray(e.target.value);&nbsp; }您可以看到您的事件处理程序对颜色更新功能进行了一次调用。然后,计算出新的颜色并将状态设置在一个位置。
随时随地看视频慕课网APP

相关分类

JavaScript
我要回答