簡體   English   中英

將字符串轉換為 JSON 或 Javascript/React 中的其他數據結構

[英]Convert string into JSON or other data structure in Javascript/React

數據來自父組件的道具:

  render() {
    return (
      <div className='App'>
        <header className='App-header'>
          <Table data={this.state.apiResponse} />
        </header>
      </div>
    );
  }

和表格組件如下。 如果像這樣發送的數據被發送到整體渲染,它會顯示在屏幕上。 這就是this.props.data樣子

class Table extends React.Component {
  constructor(props) {
    super(props);
  }

  render() {
    const { data } = this.props;
      <div>
        <table>
          <thead>
            <tr>{data}</tr>
          </thead>
        </table>
      </div>
    );
  }
}

export default Table;

當我想修改該數據時出現問題。 例如,如果在render()中添加:

console.log(typeof data) -> 返回string

所以我嘗試將其轉換為 JSON:

const convertedData = JSON.parse(data); -> 返回錯誤信息:

錯誤:引發了跨域錯誤。 React 無法訪問開發中的實際錯誤 object。

this.props.data的格式有問題嗎? 如何將其從字符串轉換為其他數據結構? (因為我需要執行mapreduce它)。

首先,您的 Table 組件需要一個 return 語句。 但是,關於原始問題,我懷疑您的 api 返回的內容與您的預期響應不同。 我使用您的預期數據創建了一個.json 文件,在應用程序中導入數據,並在應用程序內呈現表格。

當您在 Table 組件中控制台日志數據時,結果是什么。

應用程序.js

import React from 'react';
import './App.css';
import apiData from './api'
import Table from "./Table";

function App() {
     return (
        <div className="App">
             <header className="App-header">
                   <Table data={apiData} />
             </header>
        </div>
     );
}
export default App;

表.js

import React, {PureComponent} from "react";

export default class Table extends PureComponent{

    render() {
        const { data } = this.props;
        return(
            <div>
                <table>
                    <thead>
                         <tr>{data[0].game_id} {typeof data}</tr>
                    </thead>
                </table>
            </div>
        );
    }
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

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