gpt4 book ai didi

javascript - 如何在 react js中使用json在表中显示数据?

转载 作者:太空狗 更新时间:2023-10-29 15:36:46 26 4
gpt4 key购买 nike

我有类似 this 的 JSON

我想使用这个 JSON 并使用 React js 在表中显示数据。

这就是我从 JSON 文件中显示数据的方式。

import React, { Component } from 'react';
import data from './data.json';

class App extends Component {
render() {
return (
<ul>
{
data.map(function(movie){
return <li>{movie.id} - {movie.title}</li>;
})
}
</ul>
);
}
}

export default App;

如何使用 reactjs 从 URL 加载 JSON 并将其显示在表中?

最佳答案

你可以 fetch组件挂载后的 JSON,当您最终解析它时,您可以更新组件的状态:

import React, { Component } from 'react';


class App extends Component {
// initially data is empty in state
state = { data: [] };

componentDidMount() {
// when component mounted, start a GET request
// to specified URL
fetch(URL_TO_FETCH)
// when we get a response map the body to json
.then(response => response.json())
// and update the state data to said json
.then(data => this.setState({ data }));
}


render() {
return (
<ul>
{
this.state.data.map(function(movie){
return <li key={movie.id}>{movie.id} - {movie.title}</li>;
})
}
</ul>
);
}
}

export default App;

如果您无法使用fetch,您可以使用其他一些库,例如superagent。或 axios .或者你甚至可以回退到好的 ol' XMLHttpRequest

另一方面,在构建组件列表时,重要的是每个子组件都有一个唯一的 key 属性。我还在代码中更新了它,假设 movie.id

示例 axios 代码:

axios.get(URL)
.then(response => response.data)
.then(data => this.setState({ data }));

编辑:正如 trixn 在回复中所写,componentDidMount 是获取数据的首选位置。更新代码。

编辑 2:添加了 axios 代码。

关于javascript - 如何在 react js中使用json在表中显示数据?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49690735/

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