繁体   English   中英

如何在反应中使用 useState 钩子更新状态?

[英]How to update a state using useState hook in react?

我是 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

烧瓶 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 变量中的数据时,它会正确显示数据。 但是当我在状态中记录数据时,它不显示任何数据。 你能帮我解决这个问题,并建议为什么会发生这种情况。

谢谢

因为在异步中使用 setState。 状态notes仅在组件重新渲染时更新新值。 您可以在重新运行之前使用console.log检查新的note

console.log("state data",notes);    
return (...)

暂无
暂无

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

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