繁体   English   中英

使用钩子设置 React 状态时未定义

[英]React state is undefined when setting it with a hook

我是新手,我试图从下拉框中的选择中设置一个状态,但我的状态仍未定义。

这是我用于下拉列表的对象数组 (categorias.js):

export const categorias_array = [
{
  key: 1,
  text: "Primera",
  value: "1"
},
{
  key: 3,
  text: "Tercera",
  value: "3" 
},
{
  key: 4,
  text: "Cuarta",
  value: "4" 
},
{
  key: 5,
  text: "Quinta",
  value: "5" 
},
{
  key: 6,
  text: "Sexta",
  value: "6" 
},
{
  key: 7,
  text: "Septima",
  value: "7" 
}
];

这是我的代码:

import React, { Component, useState } from 'react';
import { Dropdown } from 'semantic-ui-react'
import { Select } from 'semantic-ui-react'
import { lista_jugadores } from './jsons/lista_jugadores'
import { categorias_array } from './jsons/categorias'

export default () => {

  const[categoria, setCategoria] = useState(categorias_array[0].key);


  return(
    <div>
      <Dropdown placeholder="Seleccionar divisional" options={categorias_array} value={categoria} onChange={ (e) => setCategoria(e.target.value) }/>
      <h1>Categoria:{categoria}</h1> 
    </div>
    
  );

我只是想确保在这个早期阶段,状态设置为在 h1 中可视化但不起作用,它仍然未定义。 理想情况下,我希望我的状态直接是数组类别的对象之一,但是,如果它只是值,我将能够工作。

提前致谢。

您必须使用更改处理程序的第二个参数来获取选定的 id。

像这样定义你的 handleChange,

 onChange={ (e, data) => setCategoria(data.value) }

完整代码:-

  const [categoria, setCategoria] = useState(categorias_array[0].key);

  const handleChange = (e, data) => {
    // data.value will give the selected id
    console.log(data.value);
    setCategoria(data.value);
  };
      return (
        <div>
          <Dropdown
            placeholder="Seleccionar divisional"
            options={categorias_array}
            value={categoria}
            onChange={handleChange}
          />
          <h1>Categoria:{categoria}</h1>
        </div>
      );
    };

工作演示 - https://codesandbox.io/s/rough-paper-1cvo4?file=/src/App.js:729-1154

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM