javascript 在映射返回中反应渲染数组

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/25674704/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-28 04:48:39  来源:igfitidea点击:

React Render Array in Mapped Return

javascriptarraysmapreactjs

提问by Matthew Schrepel

I have a react component that is rendering some results. The problem I am having is with result.participants. This is an array, so map is rendering both names without any spacing and I am finding it difficult to get those spaces inserted.

我有一个正在呈现一些结果的反应组件。我遇到的问题是 result.participants。这是一个数组,因此 map 渲染两个名称时没有任何空格,我发现很难插入这些空格。

The result.participants is an array of strings.

result.participants 是一个字符串数组。

How do I insert a space or some logic to put in a comma and a space if the length is >1 ?

如果长度 >1 ,如何插入空格或一些逻辑以放入逗号和空格?

render: function(){
  return (
  <ul>
    {
      this.state.pads.map(function(result){
        return [
        <a href={result.pageUrl}>{result.title}</a>,
        <li key={result.participants}>Participants: {result.participants} </li>,
        <li key={result.summary}>Summary: {result.summary}</li>,
        <li key={result.lastEdit}>Last Edited: {new Date(result.lastEdit).toDateString()} </li>,
        <p></p>
        ];
      })}
  </ul>
)
}

采纳答案by Zach

Like a commenter mentioned, you should not put bare <a>and <p>tags into a <ul>directly. But that is beside the point, this question is about array handling in React.

就像评论者提到的那样,您不应该直接将裸<a><p>标签放入 a 中<ul>。但这不是重点,这个问题是关于 React 中的数组处理。

You should be able to use a control flow structure nested in JSX like this:

您应该能够像这样使用嵌套在 JSX 中的控制流结构:

{
  result.participants.map(function(participant, idx) {
    if (idx == result.participants.length - 1) {
      return (
        <span>{participant}, </span>
      );
    } else {
      return participant;
    }
  })
}

回答by Paul O'Shannessy

And if you don't care about wrapping each participant in a <span>, you could simply use the built-in Array.prototype.joinmethod:

如果您不关心将每个参与者包装在 a 中<span>,您可以简单地使用内置Array.prototype.join方法:

<li key={result.participants}>Participants: {result.participants.join(', ')} </li>,

<li key={result.participants}>Participants: {result.participants.join(', ')} </li>,