Reactjs 基本选择组件:无法读取未定义的属性“映射”

Reactjs 基本选择组件:无法读取未定义的属性“映射”,reactjs,Reactjs,我是个新手,我正在尝试制作一个选择组件,将数组作为道具,并将其转换为s 组成部分: import React, { Component } from "react"; class Select extends Component { render() { return ( <select> {this.props.items.map((item) => ( <option>{item}

我是个新手,我正在尝试制作一个选择组件,将数组作为道具,并将其转换为s

组成部分:

import React, { Component } from "react";

class Select extends Component {
  render() {
    return (
      <select>
        {this.props.items.map((item) => (
          <option>{item}</option>
        ))}
      </select>
    );
  }
}

export default Select;
呈现:

import React from "react";
import Select from './components/Select';

function App() {
  return (
    <div className="App">
          <Select items={['Volvo', 'Subaru']} />
    </div>
  );
}

export default App;
我无法读取未定义的属性“map”。

选择组件不知道其道具中有一个项目列表,因此需要显式定义它

import React, { Component } from 'react';

interface SelectProps {
  items: any;
}

class Select extends Component<SelectProps> {    
  render() {
    return (
      <select>
        {this.props.items.map((item) => (
          <option>{item}</option>
        ))}
      </select>
    );
  }
}

export default Select;
选择组件不知道它的道具中有一个项目列表,所以您需要显式地定义它

import React, { Component } from 'react';

interface SelectProps {
  items: any;
}

class Select extends Component<SelectProps> {    
  render() {
    return (
      <select>
        {this.props.items.map((item) => (
          <option>{item}</option>
        ))}
      </select>
    );
  }
}

export default Select;

对于未定义的错误,可以使用javascripts new ES2020 feature?。也称为可选链接

  <select>
      {this.props.items?.map((item) => (
              <option>{item}</option>
      ))}
  </select>

因此,如果项目未定义,则不会出现错误

对于未定义的错误,可以使用javascripts new ES2020 feature?。也称为可选链接

  <select>
      {this.props.items?.map((item) => (
              <option>{item}</option>
      ))}
  </select>

因此,通过这种方式,如果项目未定义,则不会出现错误

Add console.logthis.props在render之后但在return语句之前,并查看您得到了什么。我尝试了您的代码,但它似乎有效,尽管有关于键的警告。因此,我猜您没有从另一个组件传递道具。您的示例在这里工作得很好:在呈现之后但在return语句之前添加console.logthis.props,并查看您得到了什么我尝试了您的代码,但它似乎工作了,尽管有关于键的警告。所以我猜你不会从另一个组件传递道具。你的例子在这里很好:这是一个很棒的特性!谢谢分享这是一个很棒的功能!谢谢分享