我有一个函数,需要返回一个带有换行符的字符串或可以正确呈现的divs
export const showPeople = (peopleArray = []) => {
let peopleString = peopleArray ? peopleArray.map((people) => {
<div>
`${people.name && people.name},
${people.last_name && people.last_name}`
</div>
}).join('') : ''
return peopleString
}
我尝试了div,没有div,没有返回,没有加入的return,并且每个人都得到了[Object],在这种情况下为空字符串
我看到过类似的问题,但无法解决我的问题
答案 0 :(得分:3)
您不想返回要返回元素数组的字符串:
let peopleString = peopleArray.map((people) => (
<div>
{people.name || ""},
{people.last_name || ""}
</div>
));
return peopleString
答案 1 :(得分:2)
axios
export const showPeople = (peopleArray = []) => {
let peopleString = peopleArray ? peopleArray.map(people =>
`<div>
${people.name}, ${people.last_name}
</div>`
).join('') : ''
return peopleString
}
var peoples = [{name: 'Jhon', last_name: 'Doe'},{name: 'Mario', last_name: 'Peach'}]
var peopleString = peoples.map(people =>
`<div>
${people.name}, ${people.last_name}
</div>`
).join('')
console.log(peopleString)
document.getElementById('container').innerHTML = peopleString
答案 2 :(得分:1)
由于您没有使用变量进行字符串连接。您需要在div中删除模板字符串。
答案 3 :(得分:1)
如果目标是将项目列表简化为呈现为多行字符串的单个字符串,则可以使用white-space:pre-wrap;
CSS规则来实现:
body {
white-space: pre-wrap;
}
完成后,您应该能够使用\n
个字符用换行符呈现多行字符串,如下所示:
export const showPeople = (peopleArray = []) => {
let peopleString = peopleArray ? peopleArray.map((people) => (
`${people.name ? people.name : ''} ${people.last_name ? people.last_name : ''}`
})
.join('\n') : ''
return peopleString
}
I've posted a working version here供您查看
希望这会有所帮助!
答案 4 :(得分:1)
在我看来,您未返回该地图功能中的任何内容:
(people) => { ...string here... }
我建议,简单地:
(people) => ( ...string here... )
或:
(people) => { return ...string here... }
另一个问题可能是您似乎打算在map函数中返回的内容不是字符串,可能应该是(?);很难在上下文中看到该功能。