【问题标题】:Can't assign const to state value, returns undefined无法将 const 分配给状态值,返回未定义
【发布时间】:2019-06-17 11:23:45
【问题描述】:

我正在尝试映射一些值,但不断收到有关 map 函数的错误。当我尝试将 const 分配为等于状态时,它变得未定义。我在控制台中记录了状态,然后返回结果:

species: Array(3)
0: {species_ID: 1, species: "Dog"}
1: {species_ID: 2, species: "Cat"}
2: {species_ID: 3, species: "Hamster"}
length: 3

但是当我尝试将它分配给渲染方法中的 const 时,记录控制台给了我未定义的信息。

我已经尝试直接在 map 方法中映射状态以避免这一步,但是得到关于 map 不是函数的错误。

{this.state.species && this.state.species.map (speciestype => {
                        return (
                        <option key={speciestype.species_ID} value={speciestype.species_ID}>
                            {speciestype.species}
                        </option>
                    )}
                    )}

这是当前代码的样子:

render() {
   const {speciesdata} = this.state.species; 
   console.log(speciesdata);
    return (

我的地图功能如下所示:

{speciesdata && speciesdata.map (speciestype => {
                        return (
                        <option key={speciestype.species_ID} value={speciestype.species_ID}>
                            {speciestype.species}
                        </option>
                    )}
                    )}

但由于 speciesdata 未定义(根据控制台),下拉列表为空。

为什么我不能将物种数据分配给我知道存在的状态?

【问题讨论】:

    标签: arrays reactjs state


    【解决方案1】:

    这个:

    const {speciesdata} = this.state.species;
    

    将不起作用,因为 this.state.species 不包含任何名为 speciesdata 的对象。你应该这样做:

    const { species } = this.state; 
    

    或者这个:

    const speciesdata = [...this.state.species]; 
    

    然后尝试以这种方式重写你的地图,它不仅会检查它是否存在,而且还会检查物种是否是一个数组:

    {
      species && 
      species.length &&
      species.map(speciestype => (
       <option key={speciestype.species_ID} value={speciestype.species_ID}>
          {speciestype.species}
       </option>
      ))
    }
    

    【讨论】:

    • 嘿,非常感谢!没有意识到您必须将 const 称为与数组相同的值,并且显然我的地图语法有错误。为什么它不需要返回函数?我有其他使用 {} 的地图,然后是返回函数。干杯!
    • 不客气!在 ES6 语法中,您可以编写 map(a =&gt; {return a})map(a=&gt; (a))。您可以在此处阅读有关箭头功能的更多信息:developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/…
    【解决方案2】:

    LiJonas 用以下代码回答了这个问题:

    这个:

    const {speciesdata} = this.state.species;
    

    将不起作用,因为 this.state.species 不包含任何名为 speciesdata 的对象。你应该这样做:

    const { species } = this.state; 
    

    或者这个:

    const speciesdata = [...this.state.species]; 
    

    然后尝试以这种方式重写你的地图,它不仅会检查它是否存在,而且还会检查物种是否是一个数组:

    {
      species && 
      species.length &&
      species.map(speciestype => (
       <option key={speciestype.species_ID} value={speciestype.species_ID}>
          {speciestype.species}
       </option>
      ))
    }
    

    【讨论】:

      猜你喜欢
      • 2019-08-05
      • 2019-12-31
      • 2022-01-25
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-11-07
      相关资源
      最近更新 更多