类型错误:无法读取未定义的属性"映射" - 处理 json 行:test.js:11



我想在测试组件中使用json文件,如下所示,但我一直收到错误:类型错误:无法读取未定义的属性"map">我在test.js组件中操作了该文件,并使用与该组件中的文件相同形式的示例const进行了尝试,结果成功了。所以我可能处理表格不对。文件的格式为:

[{"frame_number": 1, "roi0": [101.78202823559488, 99.39509279584912, 49.546951219239915, 29.728170731543948], "intensity0": 80.0, "roi1": [101.78202823559488, 99.39509279584912, 49.546951219239915, 29.728170731543948], "intensity1": 157.0},
{"frame_number": 2, "roi0": [102.56623228630755, 97.95906005049548, 50.25603182631066, 30.153619095786393], "intensity0": 80.0, "roi1": [102.56623228630755, 97.95906005049548, 50.25603182631066, 30.153619095786393], "intensity1": 158.0},
{"frame_number": 3, "roi0": [103.39336535376313, 98.20468223716023, 49.58465295946593, 29.750791775679556], "intensity0": 80.0, "roi1": [103.39336535376313, 98.20468223716023, 49.58465295946593, 29.750791775679556], "intensity1": 157.0},

App.js


import "bootstrap/dist/css/bootstrap.css";
import React from "react";
import ReactPlayer from 'react-player'

import Buttons_Footer from "./components/Buttons_Footer.js";
import LeftPane from "./components/LeftPane.js";
import Video from "./components/Video.js";
import Radio_Button from "./components/Radio_Button.js";
import Test from "./components/test.js";
//import './App.css';
class App extends React.Component {
constructor(props) {
super(props);
this.state = { apiResponse: [] };
}
// Comunicate with API
callAPI() {
fetch("http://localhost:9000/IntensityAPI") //React app talks to API at this url
.then(res => res.json())
.then(res => this.setState({ apiResponse: res }));
}
componentWillMount() {
this.callAPI();
}

render() {
return (
<div className="App">
<header className="App-header">
<div class="row fixed-bottom no-gutters">
<div class="col-3 fixed-top fixed-bottom">
<LeftPane></LeftPane>
</div>
<div class="offset-md-3">
<Buttons_Footer></Buttons_Footer>
</div>
<Test test = {this.state.apiResponse}/>
</div>
</header>
<Video></Video>
</div>
);
}
}
export default App;

测试.js

import React from "react";
const Test = (props)=> {
const keys = props.test.map(frame => Object.keys(frame));
const filteredKeys = keys.map(frame =>
frame.filter(key => new RegExp(/^roid+$/).test(key))
);
const showButtons = frameNumber => {
return filteredKeys[frameNumber].map((roi, index) => (
<div>
<label for={`roi${frameNumber}`}>{`roi${index}`}</label>
<input type="radio" id={`roi${frameNumber}`} />
</div>
));
};
return (
<div className="Test">
<div>
{" "}
frame0
{showButtons(0)}
</div>
<div>
{" "}
frame1
{showButtons(1)}
</div>
</div>
);
};
export default Test;

问题是组件Test是在api调用尚未完成时安装的。所以道具test是空的[],那么keysfilteredKeys也是空的,并且发生错误。

让我们添加一行检查filteredKeys长度

if (filteredKeys.length === 0) return null;

之后

const showButtons = frameNumber => {

为了避免这个错误,以及当api结果为空时的错误。

最新更新