对象作为 React 子级react错误无效?

IT技术 javascript reactjs react-router react-redux
2021-05-16 00:55:37

你能告诉我为什么我会收到这个错误:

对象作为 React 子对象无效(找到:带有键 {seo_val, text_val} 的对象)。如果您打算渲染一组子项,请改用数组。

我正在尝试点击httprequest 并尝试制作 dropdown 。

import React from "react";

class DropDown extends React.Component {
  constructor(props) {
    super(props);
    console.log(this.props);
  }

  render() {
    const makeDropDown = () => {
      console.log(this.data);
      return this.props.data.map(x => {
        return <option>{x}</option>;
      });
    };
    return (
      <div>
        <div>
          <select>{makeDropDown()}</select>;
        </div>
      </div>
    );
  }
}

export default DropDown;

沙盒。

2个回答

完整的错误信息:

对象作为 React 子对象无效(找到:带有键 {seo_val, text_val} 的对象)。

错误很明显,你试图在 jsx 中渲染一个包含两个键的对象:

seo_val: "..."
text_val: "..."

像这样写,(渲染你想要的值):

return <option key={x.seo_val}>{x.text_val}</option>;

工作沙箱。

看起来像是x一个对象。

尝试

import React from "react";

class DropDown extends React.Component {
  constructor(props) {
    super(props);
    console.log(this.props);
  }

  render() {

    return (
      <div>
        <div>
          <select>{
            this.props.data.map(x => {
              return (<option key={x}>echo</option>);
            })
          }</select>;
        </div>
      </div>
    );
  }
}

export default DropDown;

你会看到它有效。替换echo{x}抛出您提到的错误。