如何在React组件中把对象属性数组转换为字符串?

453 阅读2分钟

这是一个简短的教程,介绍如何在React组件中把对象属性数组转换为字符串。我们有一个来自API或固定的对象数据数组。

比如说:

const employeeList = [
    {
      firstName: "John",
      lastName: "Erwin",
      email: "john@gmail.com"

    },
{
     firstName: "Ram",
      lastName: "Kumar",
      email: "john@gmail.com"
      }
  ];

我们可以通过多种方式在React中把数组转换为字符串

在React组件中将数组转换为字符串

我们可以使用Array map函数来遍历数组中的每个对象,并将每个属性转换为字符串。

让我们看看如何在react组件中使用Array.map方法进行迭代。

组件类中的数组映射函数

  • 让我们创建一个react组件app.jsx
  • 我们有存储在反应状态对象中的数组,我们将把数组转换为字符串。
  • render 方法中,使用map 方法对对象的数组进行迭代,并构建结果对象。
  • 在render方法中,使用javascript表达式语法添加这个结果
import React, { Component } from 'react';
import { render } from 'react-dom';

class App extends Component {
    constructor(props) {
    super(props);
    this.state = {
      data:  [
    {
      firstName: "John",
      lastName: "Erwin",
      email: "john@gmail.com"

    },
{
     firstName: "Ram",
      lastName: "Kumar",
      email: "john@gmail.com"
      }
  ]
    }
    }
  render() {
    const emps = this.employeeList.map((emp,index) => 
    {emp.firstName} - {emp.lastName});

         
    return {{emps}};
  }
}

render(, document.querySelector('#app'));

这将打印出对象值的有序列表

功能组件中的数组映射功能

这是一个无状态的功能组件。

  • 在返回功能组件中,我们使用map来迭代和构建li对象,使用javascript表达式来打印
import "./styles.css";

export default function App() {
  const employeeList = [
    {
      firstName: "John",
      lastName: "Erwin",
      email: "john@gmail.com"

    },
{
     firstName: "Ram",
      lastName: "Kumar",
      email: "john@gmail.com"
      }
  ];
  return (
    
      {this.employeeList.map((emp, index) => (
        {emp.firstName}-{emp.lastName}
      ))};
    
  );
}

在react中使用reduce函数

数组中的reduce函数使用累加器来减少。这需要一个对象的数组,并将缩小的数组转换为字符串。

下面是一个语法

reduce((accumulator, currentValue) => { ... } )

你可以在这里查看更多的信息

这里是一个数组缩小的例子

import React, { Component } from 'react';
import { render } from 'react-dom';

class App extends Component {
    constructor(props) {
    super(props);
    this.state = {
      data:  [
    {
      firstName: "John",
      lastName: "Erwin",
      email: "john@gmail.com"

    },
{
     firstName: "Ram",
      lastName: "Kumar",
      email: "john@gmail.com"
      }
  ]
    }
    }
  render() {

const resultEmps = this.employeeList.reduce(((acc,curr) => 
    {curr.firstName} - {curr.lastName});
  

         
    return {{resultEmps}};
  }
}

render(, document.querySelector('#app'));

总结

在本教程中,你学到了如何在有状态和无状态组件中呈现对象数组。