首页 > 解决方案 > 在反应中从服务器获取列表组

问题描述

在我的反应应用程序中,我想从服务器获取数据并将其显示为列表。

服务器返回 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"]
};

错误消失并创建了列表。但是使用硬编码的数据而不是来自服务器的数据

标签: reactjs

解决方案


尝试使用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...
}

推荐阅读