gpt4 book ai didi

javascript - 新文件阅读器(); react 。遍历项目时

转载 作者:行者123 更新时间:2023-11-30 09:12:18 25 4
gpt4 key购买 nike

我有一个文件列表,我想为其找到 base64Data 并将其显示在每个文件的列表中。

我已经尝试了以下方法,但它不起作用,我猜主要原因是 reader.onload 是异步的。

我的代码如下所示

const App = () => {

// code....
<ul>
{Array.from(files).map(file) => {
const reader = new FileReader();
let base64Data;
reader.onload = (event: any) => {
// I want to use the result here to display
// the Base64 data string of file
console.log(event.target.result);
base64Data = event.target.result
};

reader.readAsDataURL(file);
return <p>{base64Data}</p>;
}}
</ul>
}

最佳答案

// You should load data before rendering. You can't use async functions for render

class App extends React.Component {
constructor(props) {
super(props);

this.state = {
bases: [],
};
}

async componentDidMount() {
const {files} = this.props; // Assuming you get files from props

const promises = files.map((blob) => {
return new Promise((res) => {
const reader = new FileReader();
reader.readAsDataURL(blob);

reader.onload = (e) => {
res(e.target.result);
}
});
});

const bases = await Promise.all(promises);

this.setState({bases});
}

render() {
const {bases} = this.state;

if (bases.length === 0) return 'No data';


<ul>
{bases.map(base64Data) => {
return <li>{base64Data}</li>;
}}
</ul>
}
}

关于javascript - 新文件阅读器(); react 。遍历项目时,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57677785/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com