【问题标题】:Show and map JSON object on ReactJs Table在 ReactJs 表上显示和映射 JSON 对象
【发布时间】:2018-12-04 06:07:33
【问题描述】:

我想在 JSON 对象中映射和显示我的表内容,在 ReactJS 中的表组件内。 我正在使用 React-table library 组件来显示表格,根据文档,它接受 2 个道具,即列和数据。

从 NodeJS 端点,我设法获取了 2 个对象,即:

田野

"fields": [
{
  "COLUMN_NAME": "quizID"
},
{
  "COLUMN_NAME": "question"
},
{
  "COLUMN_NAME": "choice1"
},
{
  "COLUMN_NAME": "choice2"
},
{
  "COLUMN_NAME": "choice3"
},
{
  "COLUMN_NAME": "choice4"
},
{
  "COLUMN_NAME": "answer"
}

],

和表格内容

"isi": [
{
  "quizID": 1,
  "question": "Pertanyaan",
  "choice1": "Pilihan1",
  "choice2": "Pilihan2",
  "choice3": "Pilihan3",
  "choice4": "Pilihan4",
  "answer": "Jawaban"
},
{
  "quizID": 2,
  "question": "Pertanyaan",
  "choice1": "Pilihan1",
  "choice2": "Pilihan2",
  "choice3": "Pilihan3",
  "choice4": "Pilihan4",
  "answer": "Jawaban"
}, so on--

我还设法在节点中设置了两个对象,并从反应中获取作为一个对象。这是获取脚本

componentDidMount() {
    let self = this;
    fetch('http://localhost:5000' + par, { 
        method: 'GET'
    }).then(function (response) {
        if (response.status >= 400) {
            throw new Error("Bad response from server");
        }
        return response.json();
    }).then(function (data) {
        self.setState({ dataTabel: data.fields }); //settings the fetched data to state
        self.setState({ columnTabel: data.isi });

        console.log(self.state.dataTabel)
        console.log(self.state.columnTabel)
    }).catch(err => {
        console.log('caught it!', err);
    })
}

我在 render() 中调用 React table 的组件,将 dataTabel 状态和 columnTabel 状态都作为 props,但 table 不会显示任何数据。 我试过使用地图功能,但也没有成功。

任何帮助将不胜感激。

【问题讨论】:

    标签: json node.js reactjs rest


    【解决方案1】:

    问题在于列对象。根据the documentation,您需要提供具有以下格式的对象数组中的列:

    const columns = [{
        Header: 'Name',
        accessor: 'name' // String-based value accessors!
    }, {
        Header: 'Age',
        accessor: 'age',
        Cell: props => <span className='number'>{props.value}</span> // Custom cell components!
    }]
    

    要使其正常工作,您需要以这种格式调整数据:

    const columns = [
    {
        Header: "quizID",
        accessor: "quizID"
    },
    {
        Header: "question",
        accessor: "question"
    },
    {
        Header: "choice1",
        accessor: "choice1"
    },
    {
        Header: "choice2",
        accessor: "choice2"
    },
    {
        Header: "choice3",
        accessor: "choice3"
    },
    {
        Header: "choice4",
        accessor: "choice4"
    },
    {
        Header: "answer",
        accessor: "answer"
    }
    ];
    

    您还需要调用ReactTable 组件传递数据和列,如下所示:&lt;ReactTable data={data} columns={columns} /&gt;

    HERE你可以找到一个完整的工作解决方案。

    【讨论】:

    • 我已经根据文档重新塑造了对象,并设法使它工作!谢谢!
    猜你喜欢
    • 1970-01-01
    • 2021-05-16
    • 1970-01-01
    • 1970-01-01
    • 2021-05-16
    • 2018-08-05
    • 2021-09-16
    • 2019-01-31
    • 1970-01-01
    相关资源
    最近更新 更多