admin管理员组

文章数量:1353127

I want to join all the names by using space

 const { author} = this.props;
        const authors= author.map((e, i) =>
            <div className="ck12 o6 b4" key={i}>
                <div className="authorlist">
                    <h4>{e.name}</h4>

The code looks like this. JohnTomJack I want John Tom Jack. I added e.name.join(" ") but code giving error join is not a function. I try how to render react ponents by using map and join but I could not.

I want to join all the names by using space

 const { author} = this.props;
        const authors= author.map((e, i) =>
            <div className="ck12 o6 b4" key={i}>
                <div className="authorlist">
                    <h4>{e.name}</h4>

The code looks like this. JohnTomJack I want John Tom Jack. I added e.name.join(" ") but code giving error join is not a function. I try how to render react ponents by using map and join but I could not.

Share Improve this question asked May 11, 2018 at 7:32 tom clacktom clack 1913 silver badges14 bronze badges 1
  • Can you reproduce your problem in the code snippet? – Limbo Commented May 11, 2018 at 7:35
Add a ment  | 

1 Answer 1

Reset to default 9

Good morning sir,

The function join is only applicable to an Array. Learn more about it here: https://developer.mozilla/fr/docs/Web/JavaScript/Reference/Objets_globaux/Array/join

THis function will join all the elements (in most of the cases, strings) from the array to a single string.

For your specific case since the author name is inside an object with the property name, you could do the following:

const authorNames = author.map(e => e.name).join(' ');
// authorNames will be now John Tom Jack

You will use the map method to transform that array to a new array containing only strings. Then you can join those strings with the join function.

// Example class ponent
class Thingy extends React.Component {
  render() {
    const names = [{ name: 'John'}, {name: 'Doe'}, {name: 'Snow'}];
    console.log('names', names);
    return (
      <div>
        <div>{names.map(e => e.name).join(' ')}</div>
      </div>
    );
  }
}

// Render it
ReactDOM.render(
  <Thingy />,
  document.getElementById("react")
);
<div id="react"></div>
<script src="https://cdnjs.cloudflare./ajax/libs/react/15.1.0/react.min.js"></script>
<script src="https://cdnjs.cloudflare./ajax/libs/react/15.1.0/react-dom.min.js"></script>

Hope that helps.

本文标签: javascriptHow to using arrayprototypejoin in reactjsStack Overflow