【发布时间】:2023-03-19 20:34:01
【问题描述】:
我尝试在此处寻找重置 useState 数组值,但找不到对数组值的任何引用。
尝试将下拉值从初始状态更改为 allowedState 值。我在这里使用钩子方法来设置使用setStateValues 的值。如果我评论那行代码,它会显示下拉菜单。我不明白为什么我不能使用setStateValues 方法来重置状态变量值。
我收到以下错误:
重新渲染过多。 React 限制渲染次数以防止无限循环
这里有什么问题吗?
import React, { useState } from "react";
import ReactDOM from "react-dom";
const StateSelector = () => {
const initialValue = [
{ id: 0,value: " --- Select a State ---" }];
const allowedState = [
{ id: 1, value: "Alabama" },
{ id: 2, value: "Georgia" },
{ id: 3, value: "Tennessee" }
];
const [stateOptions, setStateValues] = useState(initialValue);
// initialValue.push(...allowedState);
console.log(initialValue.length);
setStateValues(allowedState); // Not sure why cannot I reset the state in here for an array.
return (<div>
<label>Select a State:</label>
<select>
{stateOptions.map((localState, index) => (
<option key={localState.id}>{localState.value}</option>
))}
</select>
</div> ); };
const rootElement = document.getElementById("root");
ReactDOM.render(<StateSelector />, rootElement);
【问题讨论】:
-
您实际上是在设置导致重新渲染的状态,设置状态,重新渲染等。
标签: reactjs react-hooks