简体   繁体   English

在 React 中渲染字符串数组

[英]Rendering an array of strings in React

I'm trying to render a flat array of strings in a React app, via the following:我正在尝试通过以下方式在 React 应用程序中呈现一个平面字符串数组:

{array.length > 0 ? (
  <div>
    <h5>Email list</h5>
    <div
      style={{
      paddingLeft: "50px",
      float: "left",
      lineHeight: "normal",
      height: "50px",
      width: "300px"
      }}
    >
    {array.map((date, index) => {
    <p key={index}>{date}</p>;
    })}
    </div>
  </div>
) : (<></>)}

I'm struggling to understand why my map function won't render anything on screen.我很难理解为什么我的 map function 不会在屏幕上呈现任何内容。 I'm able to console log both date and index just fine, the dates definitely exist within the array and the h5 title renders as it should.我能够很好地控制台记录日期和索引,日期肯定存在于数组中,并且 h5 标题按应有的方式呈现。 However, nothing shows in the div beneath it.但是,它下面的 div 中没有显示任何内容。

If I remove the map functionality and just print a line of text, that renders.如果我删除 map 功能并仅打印一行文本,则会呈现。 Once I add the map back in, however, it returns to an empty div.但是,一旦我将 map 添加回来,它就会返回到一个空的 div。 No console logs to indicate anything is wrong, either.也没有控制台日志表明有任何问题。

Any help appreciated!任何帮助表示赞赏!

The map function needs a return statement if you are adding {} brackets.如果要添加{}括号,则 map function 需要返回语句。 Ex:前任:

{array.map((date, index) => {
  return <p key={index}>{date}</p>;
})}

I think u are not returning the JSX inside the map method.The below code will render the list of array elements我认为你没有在 map 方法中返回 JSX。下面的代码将呈现数组元素列表

   {array.map((date, index) => {
   return <p key={index}>{date}</p>;
   })}

I got one solution here you just need to change little bit in your code, you can add return statement after the map function and I hope it will work for you.我在这里有一个解决方案,您只需在代码中稍作更改,您可以在 map function 之后添加 return 语句,我希望它对您有用。

{array.map((date, index) => {
return (
      <p key={index}>{date}</p>;
      )
   })}

you can use this piece of code which is changed a bit.您可以使用这段稍作改动的代码。

https://codesandbox.io/s/currying-dust-uxu5jr?file=/src/App.js https://codesandbox.io/s/currying-dust-uxu5jr?file=/src/App.js

{ array.map((date, index) => <p key={index}>{date}</p> ) }

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM