对象无效,因为React子反应错误?

问题描述 投票:3回答:2

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

对象作为React子对象无效(找到:具有键{seo_val,text_val}的对象)。如果您要渲染子集合,请使用数组。

我试图点击http请求并尝试下拉。

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;

Sandbox.

javascript reactjs react-router react-redux
2个回答
4
投票

完整的错误消息:

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

错误很明显,您正在尝试在jsx中呈现包含两个键的对象:

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

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

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

Working sandbox.


-1
投票

看起来像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}会抛出你提到的错误。

© www.soinside.com 2019 - 2024. All rights reserved.