React 钩子 useState Array [英] React hooks useState Array

查看:24
本文介绍了React 钩子 useState Array的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我尝试在此处寻找重置 useState 数组值,但找不到任何对数组值的引用.

尝试将下拉值从初始状态更改为 allowedState 值.我在这里使用 hooks 方法来使用 setStateValues 设置值.如果我注释该行代码,它会显示下拉列表.我不明白为什么我不能使用 setStateValues 方法来重置状态变量值.

我收到以下错误:

<块引用>

重新渲染太多.React 限制渲染次数以防止无限循环

这里有什么问题吗?

 import React, { useState } from "react";从react-dom"导入 ReactDOM;const StateSelector = () =>{常量初始值 = [{ id: 0,value: " --- Select a State ---" }];const allowedState = [{ ID:1,值:阿拉巴马"},{ id: 2, value: "Georgia" },{ ID:3,值:田纳西"}];const [stateOptions, setStateValues] = useState(initialValue);//initialValue.push(...allowedState);console.log(initialValue.length);setStateValues(allowedState);//不知道为什么我不能在这里重置数组的状态.返回 (<div><label>选择一个状态:</label><选择>{stateOptions.map((localState, index) => (<option key={localState.id}>{localState.value}</option>))}</选择>

);};const rootElement = document.getElementById("root");ReactDOM.render(, rootElement);

解决方案

你不应该在渲染函数内设置状态(或做任何其他有副作用的事情).使用钩子时,您可以为此使用 useEffect.

以下版本有效:

import React, { useState, useEffect } from "react";从react-dom"导入 ReactDOM;const StateSelector = () =>{常量初始值 = [{ id: 0, value: " --- Select a State ---" }];const allowedState = [{ ID:1,值:阿拉巴马"},{ id: 2, value: "Georgia" },{ ID:3,值:田纳西"}];const [stateOptions, setStateValues] = useState(initialValue);//initialValue.push(...allowedState);console.log(initialValue.length);//****** 改变的开始 ******useEffect(() => {//不应该在渲染过程中设置状态,所以在 useEffect 中这样做.setStateValues(allowedState);}, []);//****** 变更结束 ******返回 (<div><label>选择一个状态:</label><选择>{stateOptions.map((localState, index) => (<option key={localState.id}>{localState.value}</option>))}</选择>

);};const rootElement = document.getElementById("root");ReactDOM.render(, rootElement);

这里是代码沙箱.

我假设您希望最终从某个动态源加载状态列表(否则您可以直接使用 allowedState 而根本不使用 useState).如果是这样,加载列表的 api 调用也可以进入 useEffect 块.

I tried looking for resetting useState array values in here but could not find any references to array values.

Trying to change the drop down value from initial state to allowedState values. I am using hooks method here to set the values using setStateValues. If I comment that line of code, it displays the drop down. I could not understand why cannot I use setStateValues method to reset the state variable values.

I am getting this following error:

Too many re-renders. React limits the number of renders to prevent an infinite loop

Is there something wrong in here?

    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);

解决方案

You should not set state (or do anything else with side effects) from within the rendering function. When using hooks, you can use useEffect for this.

The following version works:

import React, { useState, useEffect } 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);
  // ****** BEGINNING OF CHANGE ******
  useEffect(() => {
    // Should not ever set state during rendering, so do this in useEffect instead.
    setStateValues(allowedState);
  }, []);
  // ****** END OF CHANGE ******

  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);

and here it is in a code sandbox.

I'm assuming that you want to eventually load the list of states from some dynamic source (otherwise you could just use allowedState directly without using useState at all). If so, that api call to load the list could also go inside the useEffect block.

这篇关于React 钩子 useState Array的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
其他开发最新文章
热门教程
热门工具
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆