首页 > 解决方案 > 在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- 它返回奇怪的字符串

所以我尝试用 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;

标签: javascriptjsonreactjsparsingreact-props

解决方案


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

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

    })

推荐阅读