在 Javascript 中将字符串转换为对象

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 [

我期待第一个对象 ({"game_id":4,"city":"Pyeongchang","year":2018}) 但它从 this.props.data.

中获取了第一个字符

所以我在想数据格式不正确。

console.log(typeof this.props.data); // -> string - returns 字符串很奇怪

所以我尝试用 JSON.parse:

来转换它

const convertedData = JSON.parse(this.props.data); -> 但这会引发错误:

错误:抛出了跨源错误。 React 无法访问开发中的实际错误对象。

为什么会发生这种情况,如何解决?

更新

数据来自 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;

您应该在 componentDidMount 中调用 this.callAPI,而不是 componentWillMount。此外,将 this.state.apiResponse 初始化为空数组而不是字符串可能会更简单,因此您不必将其转换为字符串,然后返回到带有 JSON.parse[=15= 的对象]

您是否尝试过在第一次收到 API 的响应时将您的数据转换为 JSON?也许你可以试试这个

fetch(reqUrl, request)
    .then((response) => response.json())
    .then((responseJson) => {
        // your json result is here
    })
    .catch((error) => {

    })