ReactJS未定义useState文件内容



我正在从电脑上传一个本地csv文件。然后我将这个csv文件的内容存储到useState(setFileContent(中。当我在setFileContent(contentObj(行之前console.log这个文件的内容时,我得到了一个很好的对象数组,就像我想要的那样。然而,在finally中,当我console.log useState fileContent时,我得到了undefined,它还在我的文件中说fileContent是未定义的,不可能在未定义的文件上应用映射。为什么contentObj没有存储在useState文件内容中?如有任何帮助,我们将不胜感激。

function App() {
const [loading, setLoading] = useState(false)
const [fileContent, setFileContent] = useState()
const [filename, setFilename] = useState()
const handleOnChange = (f) => {
setLoading(true)
try {
const files = f.target.files;
setFilename(files["0"].name)
if (files) {
Papa.parse(files[0], {
complete: function (results) {
let content = results.data.slice(1)
let contentObj = content.map(c => ({
"ID": c[0],
"name": c[1],
"lastname": c[2],
"age": c[3],
"address": c[4],
"radius": c[5],
"lat": c[6],
"long": c[7],
}))
console.log(contentObj)
setFileContent(contentObj)
}
})
}
} catch (e) {
alert(e)
} finally {
setLoading(false)
}
};

// function to calculate the middle points 
var location = [15.47, 115.10]
return (
<Box sx={{ flexGrow: 1, backgroundColor: 'black' }}>
<div style={{ display: 'flex', justifyContent: 'center', marginTop: 10, marginBottom: 10 }}>
<Button variant="contained" component="label">
Upload a File
<input hidden accept=".csv" multiple type="file" onChange={handleOnChange} />
</Button>
</div>
<div style={{ display: 'flex', justifyContent: 'center', marginTop: 10, marginBottom: 10, color: "white" }}>
{filename}
</div>
<Grid container spacing={2}>
<Grid xs={1}></Grid>
<Grid xs={10}>
<Card
style={{
borderRadius: 10,
height: 600,
overflowX: "none",
overflowY: 'auto',
marginBottom: 1000,
marginTop: 20
}}
variant='outlined'
>
{loading ? <CircularProgress /> : <div>
<MapContainer center={location} zoom={6} scrollWheelZoom={true}>
<TileLayer
url="https://server.arcgisonline.com/ArcGIS/rest/services/World_Imagery/MapServer/tile/{z}/{y}/{x}"
/>
{fileContent && fileContent.map(e => (
<Circle
center={[e.latitude_deg, e.longitude_deg]}
pathOptions={{ color: 'red' }}
radius={e.accuracy_level == "HIGH" ? 5000 : e.accuracy_level == "MEDIUM" ? 15000 : 30000}>
</Circle>

))}
</MapContainer>
</div>}

</Card>
</Grid>
<Grid xs={1}></Grid>
</Grid>
</Box>
);
}
export default App;

别忘了setFileContent是异步函数,所以需要使用useEffect钩子来实现fileContent


useEffect(() => {
console.log(fileContent);
}, [fileContent]);

最新更新