短篇小说:我正在制作自己的GIS(地理信息系统),并且希望能够上传包含地理数据的JSON文件。但是,我不想将文件保存在数据库中,仅保存在列表中。此外,我正在使用上下文将数据解析为<MAP/>
(传单)组件。
当我将新的JSON上传到layerList
时,它会更新,但是<MAP/>
组件不会重新呈现。
我可能正在使用一种怪异的方式来更新状态,但是我不知道该怎么做。
这是我的代码
import React, {createContext, useState} from 'react';
import "../../App.css";
import data from '../../Layers/layer1.json'
import data1 from '../../Layers/layer2.json'
export const FileContext = createContext()
const layerList = [data]
function updateList(layer){
layerList.push(layer)
}
// Create an object of formData
const onFileChange = e => {
const fileReader = new FileReader();
fileReader.readAsText(e.target.files[0], "UTF-8");
fileReader.onload = e => {
updateList(JSON.parse(e.target.result));
console.log(layerList)
};
//console.log(layerList)
}
export const FileProvider = (props) => {
const [layer, setLayer] = useState(
layerList
)
return(
<FileContext.Provider value = {layer}>
{props.children}
</FileContext.Provider>
);
}
function FileUpload() {
return (
<div>
<div id='fileupload'>
<input type="file" onChange={onFileChange} />
</div>
</div>
);
}
export default FileUpload;
答案 0 :(得分:0)
您的layerList
存在并且被维护在组件范围之外。它不知道以这种方式对layerList进行了更改。您需要稍微改变一下逻辑以使其看起来像这样:
import React, {createContext, useState} from 'react';
import "../../App.css";
import data from '../../Layers/layer1.json'
import data1 from '../../Layers/layer2.json'
export const FileContext = createContext()
// Create an object of formData
const onFileChange = e => {
const fileReader = new FileReader();
fileReader.readAsText(e.target.files[0], "UTF-8");
fileReader.onload = e => {
updateList(JSON.parse(e.target.result));
console.log(layerList)
};
//console.log(layerList)
}
export const FileProvider = (props) => {
const [layerList, setLayerList] = useState([data]);
const updateList (layer) => {
setLayerList([layer, ...layerList]); //This creates a new array in memory, so it will trigger a rerender.
};
useEffect(() => {
//Update json file logic
}, [layerList])
return(
<FileContext.Provider value = {layerList, setLayerList}>
{props.children}
</FileContext.Provider>
);
}
function FileUpload() {
//change this component to be a context consumer and the 'onChange' event can fire the `setLayerList` function to update everything.
return (
<div>
<div id='fileupload'>
<input type="file" onChange={onFileChange} />
</div>
</div>
);
}
export default FileUpload;