[英]Convert string to object in Javascript
我通过道具接收一些数据:
this.props.data = [
{"game_id":4,"city":"Pyeongchang","year":2018},
{"game_id":2,"city":"Rio de Janeiro","year":2016}
];
这是接收到的内容,可以将其发送到渲染并在屏幕上显示。
问题是当我想访问这个数组的内部时。
例如:
const firstObj = this.props.data[0];
console.log('firstObj: ', firstObj); // prints [
我期待第一个 object ( {"game_id":4,"city":"Pyeongchang","year":2018}
)但它从this.props.data
中获取了第一个字符。
所以我在想数据格式不正确。
console.log(typeof this.props.data); // -> string
console.log(typeof this.props.data); // -> string
- 它返回奇怪的字符串
所以我尝试用 JSON.parse 转换它:
const convertedData = JSON.parse(this.props.data);
-> 但这会引发错误:
错误:引发了跨域错误。 React 无法访问开发中的实际错误 object。
为什么会发生这种情况,如何解决?
更新
数据来自 Node.js:
var express = require('express');
var router = express.Router();
var sqlite3 = require('sqlite3').verbose();
var db = new sqlite3.Database('./db/ocs_athletes.db');
router.get('/', function (req, res, next) {
db.serialize(function () {
db.all(
'SELECT g.game_id, g.city, g.year, ar.athlete_id, ar.gold, ar.silver, ar.bronze FROM(Game g join AthleteResult ar on g.game_id = ar.game_id) order by g.year desc',
function (err, rows) {
return res.send(rows);
}
);
});
});
module.exports = router;
在 React 应用程序中,它在 App.js 中收到:
import React from 'react';
import './App.css';
import Table from './components/Table';
class App extends React.Component {
constructor(props) {
super(props);
this.state = { apiResponse: [] };
}
callAPI() {
fetch('http://localhost:9000/testAPI')
.then((res) => res.text())
.then((res) => this.setState({ apiResponse: res }));
}
componentDidMount() {
this.callAPI();
}
render() {
return (
<div className='App'>
<header className='App-header'>
<Table data={this.state.apiResponse} />
</header>
</div>
);
}
}
export default App;
从这里它通过 props 发送到 Table 组件:
class Table extends React.Component {
constructor(props) {
super(props);
}
render() {
const { data } = this.props;
console.log('data: ', data); // prints the whole data
console.log(typeof data); // prints string
const convertData = JSON.parse(this.props.data); // throws the error I talked about
return (
<div>
<table>
<thead>
<tr>{data}</tr>
</thead>
</table>
</div>
);
}
}
export default Table;
在第一次收到来自 API 的响应时,您是否尝试过将数据转换为 JSON? 也许你可以试试这个
fetch(reqUrl, request)
.then((response) => response.json())
.then((responseJson) => {
// your json result is here
})
.catch((error) => {
})
您应该在componentDidMount
中调用this.callAPI
,而不是在componentWillMount
中。 此外,将this.state.apiResponse
初始化为空数组而不是字符串可能会更简单,因此您不必将其转换为字符串,然后使用 Z0ECD11C1D7A287401D148A23BBD 将其转换回JSON.parse
。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.