简体   繁体   English

在 ReactJs 中渲染 Flask JSON 响应

[英]Rendering Flask JSON response in ReactJs

So, I've been struggling with this and couldn't really find a solution.所以,我一直在努力解决这个问题,并没有真正找到解决方案。 I have a Flask backend that does some operations and returns a JSON response like so我有一个 Flask 后端,它执行一些操作并返回一个 JSON 响应,如下所示

server.py服务器.py

from flask import Flask
from pyresparser import ResumeParser


app = Flask(__name__)

# Details API Route
@app.route("/details")
def details():
    resume_data = ResumeParser(r'D:\React\Candetect\backend\Uploaded_Resumes\OmkarResume.pdf').get_extracted_data()
    email = resume_data.get('email')    
    return {"Information":[email]}

if __name__== "__main__":
    app.run(debug=True)

Now, I'm getting this JSON response in App.jsx like so现在,我在 App.jsx 中得到这个 JSON 响应,就像这样

  const [data, setData] = useState([])

  useEffect(() =>{
    fetch("/details").then(
      res => res.json()
    ).then(
      data => {
setData([data.Information])
        console.log(data)
      }
    )
  }, [])

And I'm trying to display it like so我试图像这样显示它

<div>
      {(data.length === 0) ? (
        <p>Loading...</p>
      ) : (
        data.members.map((member, i) => (
          <h3 key={i}>{member.email}</h3>
        ))
      )}
    </div>
    </div>

The problem, the page loads up, I get loading... message displayed, then as the data is fetched I get this error TypeError: Cannot read properties of undefined (reading 'map')问题,页面加载,我正在加载...显示消息,然后在获取数据时出现此错误TypeError: Cannot read properties of undefined (reading 'map')

For some reason it's considering it to be undefined.出于某种原因,它认为它是未定义的。

This is what I get when I console.log(data)这就是我在 console.log(data) 时得到的

{
    "Information": [
        "omkarpathak27@gmail.com"
    ]
}

Effects let you run some code after rendering so that you can synchronize your component with some system outside of React效果让您在渲染后运行一些代码,以便您可以将组件与 React 之外的某些系统同步

So basically, when your code will run for the first time, the code inside useEffect won't run.所以基本上,当你的代码第一次运行时, useEffect 里面的代码不会运行。 Using something like this, you can have a fallback render until your data loads.使用类似的东西,您可以在数据加载之前进行后备渲染。

    if (!data) {
return <p>Loading...</p>;
    }

A better solution would be to have a loading state that keeps track of the data that is being loaded.更好的解决方案是有一个加载状态来跟踪正在加载的数据。

const [data, setData] = useState([]);
const [loading, setLoading] = useState(true);

useEffect(() => {
    fetch("/details")
        .then((res) => res.json())
        .then((data) => {
            setData([data.Information]);
            setLoading(false);
            console.log(data);
        });
}, []);

if (loading && !data) {
    return <p>Loading...</p>;
}

if (!loading && !data) {
    return <p>Opps. Something`s wrong</p>;
}

return (
    <div>
        {data.members.map((member, i) => (
            <h3 key={i}>{member.email}</h3>
        ))}
    </div>
);

React v18 Fix反应 v18 修复

If you have the problem of useEffect firing twice, you can use something like to prevent it from doing that.如果你有 useEffect 触发两次的问题,你可以使用类似的东西来阻止它这样做。

function App() {
  const effectRan = useRef(false);

  useEffect(() => {
    if (effectRan.current === true || process.env.NODE_ENV !== "development") {
      //
      //Code that should only run once !
      //
    }
    return () => (effectRan.current = true);
  }, []);

  return <p></p>;
}

export default App;

So I ended up switching my code a bit.所以我最终改变了我的代码。 Here's what I did instead:这是我所做的:

App.jsx应用程序.jsx

const [initialData, setInitialData] = useState([{}])

useEffect(() => {
    fetch('/details').then(
      response => response.json()
    ).then(data => setInitialData(data))
  }, []);

  return (
      <div>
        <h3>Hello {initialData.name}</h3>
      </div>
    </div>
  );

Then, in server.py然后,在 server.py

from flask import Flask

app = Flask(__name__)

# Details API Route
@app.route("/details")
def details():
    data = func(r'path\to\pdf').get_data()
    return {"email":data.get('email'),
            "mobile_number":data.get('mobile_number'),
            "name":data.get('name'),
    }

if __name__== "__main__":
    app.run(debug=True)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM