简体   繁体   English

将字符串转换为 Javascript 中的 object

[英]Convert string to object in Javascript

I'm receiving through props some data:我通过道具接收一些数据:

this.props.data = [
         {"game_id":4,"city":"Pyeongchang","year":2018},
         {"game_id":2,"city":"Rio de Janeiro","year":2016}
];

this is what is received and it can be sent to render and show it on the screen.这是接收到的内容,可以将其发送到渲染并在屏幕上显示。

The problem is when I want to access inside of this array.问题是当我想访问这个数组的内部时。

For example:例如:

const firstObj = this.props.data[0];
console.log('firstObj: ', firstObj); // prints [

I was expecting to the the first object ( {"game_id":4,"city":"Pyeongchang","year":2018} ) but it took the first char from this.props.data .我期待第一个 object ( {"game_id":4,"city":"Pyeongchang","year":2018} )但它从this.props.data中获取了第一个字符。

So I was thinking that the data is not well formatted.所以我在想数据格式不正确。

console.log(typeof this.props.data); // -> string console.log(typeof this.props.data); // -> string - it returns string which is weird console.log(typeof this.props.data); // -> string - 它返回奇怪的字符串

So I tried to convert it with JSON.parse:所以我尝试用 JSON.parse 转换它:

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

Error: A cross-origin error was thrown.错误:引发了跨域错误。 React doesn't have access to the actual error object in development. React 无法访问开发中的实际错误 object。

Why is this happening and how can it be solved?为什么会发生这种情况,如何解决?

UPDATE更新

Data is coming from Node.js:数据来自 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;

and in React app it is received in App.js:在 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;

From here it is send through props to Table component:从这里它通过 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;

have you tried to convert your data to JSON when first receiving the response from the API?在第一次收到来自 API 的响应时,您是否尝试过将数据转换为 JSON? maybe you can try this也许你可以试试这个

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

    })

you should invoke this.callAPI in componentDidMount , not componentWillMount .您应该在componentDidMount中调用this.callAPI ,而不是在componentWillMount中。 Also, it would probably be simpler to initialize this.state.apiResponse as an empty array rather than a string so you don't have to convert it to a string and then back to an object with JSON.parse此外,将this.state.apiResponse初始化为空数组而不是字符串可能会更简单,因此您不必将其转换为字符串,然后使用 Z0ECD11C1D7A287401D148A23BBD 将其转换回JSON.parse

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM