const [photo, setPhoto] = React.useState([]); const addPhoto = async (e) => { await setPhoto(e.target.files); }; const returnPhoto = () => { if (photo.length > 0) { for (let i = 0; i < photo.length; i++) { return( <div style={{background: '#303030', display: 'inline-flex'}}> <img alt='pic' style={{maxHeight: '10em', maxWidth: '10em'}} src={URL.createObjectURL(photo[i])}/> </div> )}}}¿Alguien ve lo que hice mal? Estoy tratando de devolver los archivos seleccionados actuales de useState... Supongo que debería modificar la función addPhoto() pero hasta ahora no sé cómo.
Su principal problema es que poner return en un bucle for regular sale del bucle en la primera iteración. Querría usar algo como map() para devolver una matriz de elementos JSX.
Debido a que la propiedad de files es una Lista de archivos, no podrá usar map() directamente, pero puede convertirlo en una matriz.
También puede optimizar esto memorizando las URL creadas
const [ photos, setPhotos ] = useState([]); // really think this should be plural const addPhoto = (e) => { // no need for async setPhotos(e.target.files); }; // photos is a FileList so convert to an array const photoUrls = useMemo(() => Array.from(photos, URL.createObjectURL), [ photos ]); useEffect(() => () => { // cleanup photoUrls.forEach(URL.revokeObjectURL); }, [ photoUrls ]); const returnPhoto = () => photoUrls.map(url => ( <div style={{background: "#303030", display: "inline-flex"}}> <img src={url} alt="pic" style={{maxHeight: "10em", maxWidth: "10em"}} /> </div> ));