如何渲染对象数组?

时间:2019-04-30 11:19:24

标签: javascript reactjs

我的控制台出现这样的错误:

  

对象作为React子对象无效(找到:带有键{id,   marketId,标题,图片,语言,标志,完成,日期,费率,   类别})。如果您打算渲染儿童集合,请使用   而不是数组。

这是我后面的数据:

const demoCompletedData = [
  {
    id: 1,
    marketId: "1111-1111-1111-1111",
    title: "Autonomous car",
    picture: "https://th?id=OIP.fdvfdvfdvfdvfd&pid=Api",
    language: "English",
    flag: "",
    completed: true,
    date: "22/01/2019 10:30",
    rate: 9.1,
    categories: {
      de: 1,
      sp: 2,
      uk: 0,
      fr: 1,
      us: 4,
    },
  },

我前面的代码使用redux:

  fetchDemo() {
    this.props.demoFetchRequest();
    const { marketId } = this.props.match.params;
    axios.get(`/api/v1/passport-authenticate/market/${marketId}`)
      .then((res) => { return res.data; })
      .then(demo => this.props.demoFetchSuccess(demo))
      .catch(error => this.props.demoFetchError(error));
  }

我的渲染代码:

const { demo } = this.props;

和我的代码作为回报:

{demo}

如何映射键类别并读取其值?

2 个答案:

答案 0 :(得分:1)

您的数据是一个对象数组。您不能像这样直接渲染它。在阵列上map并渲染您要显示的内容。

{demo.map(el => (
    <div>
        <p>{el.id}</p>
        <p>{el.title}</p>
        {Object.keys(el.categories).map(key => (
            <p>{key}:{el.categories[key]}</p>
        ))}
    </div>
))}

const demo = [
  {
    id: 1,
    marketId: "1111-1111-1111-1111",
    title: "Autonomous car",
    picture: "https://th?id=OIP.fdvfdvfdvfdvfd&pid=Api",
    language: "English",
    flag: "",
    completed: true,
    date: "22/01/2019 10:30",
    rate: 9.1,
    categories: {
      de: 1,
      sp: 2,
      uk: 0,
      fr: 1,
      us: 4
    }
  }
];

const App = () => (
  <div>
    {demo.map(el => (
      <div>
        <p>{el.id}</p>
        <p>{el.title}</p>
        {Object.keys(el.categories).map(key => (
          <p>
            {key}:{el.categories[key]}
          </p>
        ))}
      </div>
    ))}
  </div>
);

ReactDOM.render(<App />, document.getElementById("root"));
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/16.6.3/umd/react.production.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/16.6.3/umd/react-dom.production.min.js"></script>
<div id="root"/>

答案 1 :(得分:0)

您的演示变量是一个数组。您需要遍历使用地图。

{demo.map(item => <div>{item.title}</div>)}

另外,ajax调用响应也需要以props只读的状态存储。

axios.get('/url')
 .then((response) => {
   console.log(response);
   this.setState({demo: response.data})
 })
.catch((error)=>{
   console.log(error);
});

在渲染中,访问方式为

const {demo} = this.state;
相关问题