开发者问题收集

TypeError:无法读取未定义的属性'map',我想使用map实现选择选项,但是有一个问题

2020-09-24
62

错误代码 :

TypeError: Cannot read property 'map' of undefined
PatientInfoModal
D:/test/pages/patient/PatientInfoModal.js:164
  161 |                </Form.Item>
  162 | 
  163 |                <Form.Item name={['patient', 'hospital']} label="Hospital" rules={[{ required: 
                                        true }]}>
> 164 |                     <Select placeholder="Select a Hospital" style={{ width:'150px' }}>
      | ^  165 |                     {testplz.map(a => <Option>{a.name}</Option>)}
  166 |                    </Select>
  167 |                </Form.Item>

mycode.js :

  const doctorplz = { doctor }
  const [ whats, whatsdata ] = useState("doctor")
  const testplz = doctorplz[whats]

  <Select placeholder="Select a Hospital" style={{ width:'150px' }}>
  {testplz.map(a => <Option>{a.name}</Option>)}
  </Select>

console.log(doctorplz) :

{doctor: Array(4)}
doctor: Array(4)
0: {d_code: 1, name: "test1", position: "RB", code_id: 1}
1: {d_code: 2, name: "test2", position: "LB", code_id: 2}
2: {d_code: 3, name: "test3", position: "ST", code_id: 2}
3: {d_code: 4, name: "test4", position: "RW", code_id: 1}
length: 4
__proto__: Array(0)
__proto__: Object

尽管我正确输入了代码,但仍然出现错误。 我不知道到底出了什么问题。

此外,下面的代码运行正常。

mycode2.js(有效的代码)

const namelist = {
    "01": [
      { d_code: '1', name: 'test1' },
      { d_code: '2', name: 'test2' },
      { d_code: '3', name: 'test3' }
    ]
  }

const [ data, setData ] = useState("01");
const Options = namelist[data];

<Select placeholder="Select a Doctor" style={{ width:'150px' }} >
{Options.map(a => <Option>{a.d_code}</Option>)}
</Select> 

console.log(namelist) :

{01: Array(3)}
01: Array(3)
0: {d_code: "1", name: "test1"}
1: {d_code: "2", name: "test2"}
2: {d_code: "3", name: "test3"}
length: 3
__proto__: Array(0)
__proto__: Object

运行 console.log() 时,两个数据的格式完全匹配。

但我不知道为什么会出现地图错误。这段代码有什么问题吗?

添加 console.log(doctor) :

(4) [{…}, {…}, {…}, {…}]
0: {d_code: 1, name: "test1", position: "RB", code_id: 1}
1: {d_code: 2, name: "test2", position: "LB", code_id: 2}
2: {d_code: 3, name: "test3", position: "ST", code_id: 2}
3: {d_code: 4, name: "test4", position: "RW", code_id: 1}
length: 4
__proto__: Array(0)
2个回答

testplz 最初可能为空,请尝试添加验证

 {testplz && Array.isArray(testplz) && testplz.map(a => <Option>{a.name}</Option>)}
kiranvj
2020-09-24

我猜你正在将医生字段作为道具获取。如果是这样,那么它有可能未定义。在这种情况下,undefined.map() 将给出错误。因此,您可以执行简单检查,然后使用 map 函数

{ testplz ? 
           testplz.map( (data, index) => <Option key={index}>{data.name}</Option>:<p>Loading...<p>} 
Himanshu Tariyal
2020-09-24