英文:
React: Why does map() iterate through all the elements on the same line instead of printing on different lines?
问题
我有一个名字的数组,我在一个函数内部像这样添加元素:
```jsx
const [names, setNames] = useState([]);
for (const file of allFiles) {
setNames([...names, String(file)]);
}
return (
{names && names.map((name) => (
<p>{name}</p>
))}
)
让我困惑的是,打印到网站上的是每个文件名,一个接一个地显示在同一行上。所以每个新的名字都会替代上一个,直到达到最后一个名字,唯一显示的是最后一个名字。然而,我想要在新的一行上显示每个名字。我应该如何实现这个?
<details>
<summary>英文:</summary>
I have an array of names to which I add elements like this within a function:
const [names, setNames] =useState([])
for (const file of allFiles){
setNames([...names, String(file)])
}
return (
{names && names.map((name) => (
<p>{name}</p>
))}
)
What puzzles me is that what gets printed to the website is every file name, one after the other on the same line. So every new name replaces the last until we reach the last name, and the only name that appears is the last name. However, I'd like to display every name on a new line. How can I achieve this?
</details>
# 答案1
**得分**: 1
我不确定你是如何组织你的代码的,但你需要在循环或使用`allFiles`数组进行文件逻辑后,在最后只设置一次`names`状态。
只需执行`setNames(allFiles)`来表示状态中的所有文件,这很简单。
此外,如果你需要在表示文件的状态更改时执行一些代码,或者在页面首次加载时执行一些代码,我建议你查看`useEffect`钩子。
<details>
<summary>英文:</summary>
I'm not sure how you're structuring your code, but you need to set the state `names` only once at the end after your loop / your logic with files using the `allFiles` array.
It's as simple as doing `setNames(allFiles)` for the state to represent all the files in an array.
Also if you need to execute some code whenever the state that represents the files changes, or whenever the page is initially loaded, I suggest you look into the `useEffect` hook.
</details>
# 答案2
**得分**: 0
如其他答案中提到的,您可能想要查看类似这样的内容:
```javascript
import React from 'react';
import { useState, useEffect } from 'react';
export function App(props) {
const allFiles = ['fileone.jpg', 'filetwo.jpg', 'filethree.jpg']
const [names, setNames] = useState([]);
useEffect(() => {
setNames(allFiles.map((file) => String(file)))
}, []);
return (
names.map((name) => (<p key={name}>{name}</p>))
);
}
英文:
as mentioned in other answers you might want to look at something like this:
import React from 'react';
import { useState, useEffect } from 'react';
export function App(props) {
const allFiles = ['fileone.jpg','filetwo.jpg','filethree.jpg']
const [names, setNames] = useState([]);
useEffect(() => {
setNames(allFiles.map((file) => String(file)))
}, []);
return (
names.map((name) => (<p key={name}>{name}</p>))
);
}
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论