gpt4 book ai didi

javascript - 获取 url 到 React 组件

转载 作者:行者123 更新时间:2023-11-30 11:23:44 24 4
gpt4 key购买 nike

我被 React 基础知识困住了:/里面有生成json数据表的代码:

import React from 'react'    
import { DataTable } from 'react-data-components';

function buildTable(data) {
const tableColumns = [
{ title: 'Author', prop: 'author' },
{ title: 'Country', prop: 'country' },
{ title: 'Title', prop: 'title' },
];

return (
<DataTable
className="container"
keys="id"
columns={tableColumns}
initialData={data}
initialPageLength={5}
/>
);
}


let url = 'https://api.myjson.com/bins/1sbz3lp';

fetch(url)
.then(res => res.json())
.then((rows) => {
ReactDOM.render(buildTable(rows), document.getElementById('root'));
});

它在 index.js 中完成了工作,但是否可以在 React 组件中呈现表格?

const Home = () => (
//renders buildTable(rows)
)

export default Home

非常感谢所有可能的帮助,期待。

最佳答案

buildTable() 移动到 Home.js 然后在 index.js 中渲染 Home 组件,传递 rows 作为 Prop :

Home.js

import React from 'react'    
import { DataTable } from 'react-data-components'

function buildTable(data) {
const tableColumns = [
{ title: 'Author', prop: 'author' },
{ title: 'Country', prop: 'country' },
{ title: 'Title', prop: 'title' },
]

return (
<DataTable
className="container"
keys="id"
columns={tableColumns}
initialData={data}
initialPageLength={5}
/>
)
}

const Home = props => buildTable(props.data)

export default Home

index.js

import ReactDOM from 'react-dom'
import Home from './Home'

let url = 'https://api.myjson.com/bins/1sbz3lp'

fetch(url)
.then(res => res.json())
.then(rows => {
ReactDOM.render(<Home data={rows} />, document.getElementById('root'));
})

编辑 Stateful Home 组件

Home.js

import React, { Component } from 'react'
import { DataTable } from 'react-data-components'

const url = 'https://api.myjson.com/bins/1sbz3lp'

class Home extends Component {
state = {
data: []
}

buildTable = (data) => {
const tableColumns = [
{ title: 'Author', prop: 'author' },
{ title: 'Country', prop: 'country' },
{ title: 'Title', prop: 'title' },
]

return (
<DataTable
className="container"
keys="id"
columns={tableColumns}
initialData={data}
initialPageLength={5}
/>
)
}

componentDidMount() {
fetch(url)
.then(res => res.json())
.then((rows) => {
this.setState({ data: rows })
})
}

render() {
return <div>{this.buildTable(this.state.data)}</div>
}
}

export default Home

关于javascript - 获取 url 到 React 组件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48826797/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com