csv ReactJS未定义的使用状态文件内容

e3bfsja2  于 2022-12-06  发布在  React
关注(0)|答案(1)|浏览(128)

我正在从我的计算机上传一个本地csv文件。然后我将此csv文件的内容存储到useState(setFileContent)。当我console.log这个档案的内容在setFileContent行之前时(contentObj),我得到了一个很好的对象数组,就像我想要的那样。但是,在finally中,当我console.log useState fileContent时,我得到了undefined,它也在我的中声明fileContent是undefined,并且不可能在undefined上应用map。为什么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;
0g0grzrc

0g0grzrc1#

不要忘记setFileContent是异步函数,因此您需要使用useEffect钩子来实现fileContent

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

相关问题