reactjs - 在反应中从服务器获取列表组
问题描述
在我的反应应用程序中,我想从服务器获取数据并将其显示为列表。
服务器返回 json 如下:
{
"files":["a.txt","b.txt","c.txt"]
}
我的代码看起来像:
import React ,{ Component }from "react";
import ReactPlayer from "react-player";
import ListGroup from "react-bootstrap/ListGroup";
import "bootstrap/dist/css/bootstrap.css";
function Watch() {
const cardContent = {
display: "flex",
flexDirection:"row",
alignItems: "center" ,
justifyContent: 'flex-end',
cursor:'pointer'
};
const gridConainer={
display:'grid',
gridTemplateColumns: 'auto auto'
};
getFiles();
let state;
function getFiles(){
fetch("http://localhost:5000/get_videos_list")
.then(res => res.json())
.then(
(result) => {
state=result;// < --- here I'm taking the array from server
},
(error) => {
console.log(error);
}
)
}
return (
<React.Fragment>
<ul className="list-group">
{state.files.map(listitem => (
<li className="list-group-item list-group-item-primary">
{listitem}
</li>
))}
</ul>
</React.Fragment>
);
}
export default Watch;
但我收到错误:
TypeError:无法读取未定义的属性“文件”
当我输入 haedcoded 时:
let state = {
files: ["Spring", "Summer", "Fall"]
};
错误消失并创建了列表。但是使用硬编码的数据而不是来自服务器的数据
解决方案
尝试使用useState
钩子。
import React ,{ useState } from "react";
//Rest of the imports...
function Watch() {
const [state, setState] = useState({});
//Rest of the code...
//let state; => remove this
function getFiles(){
fetch("http://localhost:5000/get_videos_list")
.then(res => res.json())
.then(
(result) => {
setState(result);
},
(error) => {
console.log(error);
}
)
}
//Rest of the code...
}
推荐阅读
- javascript - “T”类型的参数不能分配给“字符串”类型的参数
- windows - Python中退出方法的全面证明
- r - 我可以将 ctree 拆分规则和终端节点图存储在表中吗?
- javascript - netty-socketio 客户端 javascript 客户端连接事件不会触发
- mysql - 如何将 mysql 数据库链接到 kubernetes 上的持久卷
- android - 将用户链接到他们在 Firebase 中的数据的最佳方式?
- java - 在 Android Studio 中使用 while 循环显示带有 textview 对象的数据
- html - 如何使用 HTML CSS 创建半圆/椭圆?像仪表/速度计
- reactjs - GatsbyJS:createPage 模板中的组件
- python - Django rest 框架 + cpanel 的应用程序管理器(phusion 乘客)= 错误 500