我是 React 的初学者,我正在尝试使用 useState Hook。我有一个反应文件,我正在从烧瓶中的数据库中获取数据,它看起来像这样
import React, {useState, useEffect,useContext } from 'react'
import { Context } from "../../store/appContext"
function Main() {
const {store, actions} = useContext(Context)
const [notes, updateNotes] = useState([])
let arr =[];
const Notes = async () => {
const resp = await fetch('/main/', {
method: "GET",
mode: 'cors',
headers: {
'Content-Type': 'application/json',
'Authorization':"Bearer " + store.token
},
});
if(resp.status === 200) {
const data = await resp.json();
arr = data.data
arr.forEach(note => {
updateNotes(...notes, note);
})
console.log("Array data",arr)
updateNotes(...notes, arr);
console.log("state data",notes);
}
}
useEffect(() => {
actions.getTokenAfterRefresh();
Notes();
}, []);
return (
<>
HEy this is thee main page!!!
<div>
Welcome {store.user}!
</div>
<div>
{/* {numNotes == 0 ?
<div>
Create a new note
</div>
:
<div>
Display notes
</div> */}
}
</div>
</>
)
}
export default Main
flask api 如下所示:
from flask import (request, Blueprint, jsonify, g)
from flask_jwt_extended import jwt_required
from flask_jwt_extended import get_jwt_identity
from PIM.db import get_db
bp = Blueprint('main', __name__, url_prefix='/main')
@bp.route('/',methods=('GET', 'POST'))
@jwt_required()
def mainPage():
num=0;
data =[];
if request.method == 'GET':
db = get_db()
user = get_jwt_identity()
if user is not None:
userdata = db.execute('SELECT Info, Title from UserNotes INNER JOIN Users ON Users.Id = UserNotes.user WHERE Users.username = ?',[user]).fetchall()
for row in userdata:
data.append(list(row));
return jsonify({'data': data}), 200
当我尝试控制台记录 arr 变量中的数据时,它会正确显示数据。但是当我在状态中记录数据时,它不显示任何数据。 能否请您帮我解决这个问题,并说明发生这种情况的原因。
谢谢
答案 0 :(得分:0)
因为 setState 是异步的。状态 notes
仅在组件重新渲染时更新新值。您可以在重新运行之前使用 note
检查 console.log
的新值`
console.log("state data",notes);
return (...)