【问题标题】:Display data json to table in react在反应中将数据json显示到表中
【发布时间】:2018-05-21 17:25:09
【问题描述】:

我打算用 react js 构建一个 web。我对反应很陌生,所以我有一个问题要制作CRUD。首先,我想在表格中显示一些数据json。我有名为keranjang.js 的文件.js。它包含用于显示表格的 jsx。我还有另一个名为barang.js 的方法,我想用名为tampildata() 的方法填充它,该方法用于保存json 数据,例如{"nama_barang" : "bolu", "harga" : "10000"}。我怎么写方法?以及如何调用方法和数据以将该数据显示到keranjang.js 中的现有表中?希望大家帮帮我。

【问题讨论】:

  • 你能发布一些代码来展示你已经尝试过的东西吗?
  • 您正在尝试访问一个返回 json 的 js 文件中存在的方法,并希望在另一个具有表 ui 的 js 文件中显示该 json。对吗?
  • 是的,兄弟

标签: javascript json reactjs user-interface frontend


【解决方案1】:

我假设您尝试在当前组件中调用外部文件的方法。在您的 barang.js 文件中导出包含 json 数据的函数,例如

export function tampildata() {
    return [{ "firstname": "first", "lastname": "f"}, {"firstname": "second", "lastname": "l"}];
}

export default {
  tampildata() {
    return [{ "firstname": "first", "lastname": "f"}, {"firstname": "second", "lastname": "l"}];
  }
};

然后在您的keranjang.js 文件中导入您的tampildata 方法并在componentDidMount 中调用该方法并设置如下状态

import React from 'react';
import ReactDOM from 'react-dom';
import { tampildata } from 'barang';

class TableComponent extends React.Component {
    constructor(props) {
        super(props)
        this.state = {
            json: []
        }
    }

    componentDidMount() {
        this.setState((prevState) => {
            return {
                json: tampildata()
            }
        })
    }

    render() {
        return (
            <div>
                <table>
                    <thead>
                        <th>First Name</th>
                        <th>Last Name</th>
                    </thead>
                    <tbody>
                        {this.state.json.map((data, i) => {
                            return (
                                <tr key={i}>
                                    <td>{data.firstname}</td>
                                    <td>{data.lastname}</td>
                                </tr>
                            )
                        })}
                    </tbody>
                </table>
            </div>
        )
    }
}


ReactDOM.render(
  <TableComponent />, 
  document.getElementById("app")
);

这是工作的jsfiddle。希望对您有所帮助!

【讨论】:

  • 嘿,但我从第一个 .js 文件导出方法时遇到问题。如何导出方法?这是 ..export 函数 tampildata() {}.. 到底要写吗?因为有错误。它说“意外的令牌”
  • 是的,这种方式export function tampildata() {}导出方法和导入方法为import { tampildata } from 'barang';
  • 请查看对您有帮助的更新答案!确保你的 webpack 配置中有 presets: ['es2015', 'react', 'babel-preset-stage-0']
  • 如何配置 webpack?
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2019-07-04
  • 1970-01-01
  • 1970-01-01
  • 2020-02-03
  • 2018-03-22
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多