簡體   English   中英

將字符串轉換為 Javascript 中的 object

[英]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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM