gpt4 book ai didi

javascript - React 应用程序未按预期对更改使用react。为什么?

转载 作者:行者123 更新时间:2023-11-30 14:05:10 25 4
gpt4 key购买 nike

伙计们。我可能有一个菜鸟问题,但我还是会开枪。下面的代码片段非常简单,我不应该有问题,但我们开始吧。我正在尝试获取 ColorsGrid 组件中的颜色列表。简而言之,当用户通过下拉列表更改难度级别时,应该生成并显示一组新的颜色。我认为这是一个非常简单的练习,但事情并没有按预期进行。每当我更改难度时,它都不会使用react(重新渲染 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;
}
}

// Colors grid component
function ColorsGrid({ difficulty, colorsList }) {
return (
<div>
<strong>Colors Grid</strong>
<p>Difficulty: {difficulty}</p>
<div>
{colorsList.length > 0 ? (
colorsList.map(color => (
<div
style={{
backgroundColor: color,
height: '3rem',
width: '3rem',
borderRadius: '50%',
}}
key={color}
/>
))
) : (
<div>Loading colors...</div>
)}
</div>
</div>
);
}

// Main component
class App extends Component {
constructor(props) {
super(props);

this.state = {
difficulty: 'easy',
colorsList: [],
};

this.colorsArray = this.colorsArray.bind(this);
this.handleChange = this.handleChange.bind(this);
}

componentDidMount() {
this.colorsArray(this.state.difficulty);
}

colorsArray() {
const colors = colorsList(colorsListLength(this.state.difficulty));
const colorToGuess = randomColorToGuess(colors);

this.setState(() => ({
colorsList: colors,
gameTries: numberOfTries(this.state.difficulty),
colorToGuess,
}));
}

handleChange(e) {
this.setState({
difficulty: e.target.value,
});

this.colorsArray(this.state.difficulty); // I was under the impression the (difficulty) state had already been updated here
}

render() {
return (
<div className="App">
<h1>Colors</h1>
<div style={{ textAlign: 'right' }}>
<select
id="difficulty"
value={this.state.difficulty}
onChange={this.handleChange}
>
<option value="easy">Easy</option>
<option value="medium">Medium</option>
<option value="hard">Hard</option>
<option value="expert">Expert</option>
</select>
</div>
<ColorsGrid
colorsList={this.state.colorsList}
difficulty={this.state.difficulty}
/>
</div>
);
}
}

const rootElement = document.getElementById('root');
ReactDOM.render(<App />, rootElement);

最佳答案

这是因为 setState()异步:

setState(newState, callback);

为了获得刚刚选择的难度,您必须像这样更改代码:

this.setState({
difficulty: e.target.value,
}, () => this.colorsArray(this.state.difficulty)
);

关于javascript - React 应用程序未按预期对更改使用react。为什么?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55572885/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com