You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

React中如何从查询类获取数据库数据并在展示类渲染?

解决方案:在React组件间传递数据库查询结果

你现在的问题核心是如何把FindUser里查到的数据库数据传递给ShowProfile的state,原来直接实例化FindUser的方式不符合React的状态管理逻辑,我给你两种实用的解决思路,看哪种更适合你的场景:


方案1:把FindUser改成纯数据工具类(推荐,因为它不需要渲染UI)

首先,你的FindUser类其实只是负责数据查询,不需要作为React组件(毕竟它不用渲染任何界面),所以把它改成普通的工具类,让查询方法返回Promise,这样ShowProfile就能拿到结果并更新自己的state。

改造FindUser类

// FindUser.js
class FindUser {
  findUser(cf) {
    const params = { "Person.FiscalCode": cf };
    // 这里返回你的数据库查询Promise(比如axios、fetch或者你用的数据库SDK)
    return /* 你的数据库请求代码 */
      .then(response => {
        const utente = response.docs[0];
        console.log("name: ", utente.Person.FirstName); // 修正你原来的变量名错误(utente写成了user)
        return utente.Person; // 返回需要的用户信息对象
      })
      .catch(error => {
        console.error("查询用户失败:", error);
        throw error; // 抛出错误,让调用方可以处理
      });
  }
}

export default FindUser;

改造ShowProfile组件

在ShowProfile里,我们在合适的生命周期(比如componentDidMount)或者触发时机(比如用户输入完查询码后)调用FindUser的方法,拿到数据后用setState更新状态,进而渲染到界面上:

// ShowProfile.js
import React, { Component } from "react";
import FindUser from './FindUser';
import { View, Text, KeyboardAwareScrollView } from 'react-native'; // 假设你用的是React Native
import styles from './styles'; // 导入你的样式文件
import visualProfilo from './visualProfilo';

class ShowProfile extends Component{
  constructor(props) { // 修正你原来的拼写错误:construct → constructor
    super(props);
    // 初始化状态
    this.state = {
      FirstName: '',
      LastName: ''
    };
    this.findUserInstance = new FindUser();
  }

  componentDidMount() {
    // 这里替换成实际的查询码来源(比如从props传入、用户输入等)
    const targetCf = "要查询的用户FiscalCode";
    // 调用查询方法,更新state
    this.findUserInstance.findUser(targetCf)
      .then(userData => {
        this.setState({
          FirstName: userData.FirstName,
          LastName: userData.LastName
        });
      });
  }

  render() {
    return (
      <View style={styles.container}>
        <KeyboardAwareScrollView>
          <View style={styles.page}>
            <Text style={visualProfilo.text}>Name:</Text>
            <Text style={visualProfilo.text1}>{this.state.FirstName}</Text>
            <Text style={visualProfilo.text}>Surname:</Text>
            <Text style={visualProfilo.text1}>{this.state.LastName}</Text>
            {/* 其他需要展示的内容 */}
          </View>
        </KeyboardAwareScrollView>
      </View>
    )
  }
}

export default ShowProfile;

方案2:让FindUser作为组件,通过回调传递数据(适合需要显示加载状态的场景)

如果你确实需要让FindUser作为React组件(比如要在查询时显示加载动画),可以通过父组件传回调函数的方式把数据传递给ShowProfile:

改造FindUser组件

// FindUser.js
import React, { Component } from "react";

class FindUser extends Component {
  componentDidMount() {
    const { cf, onUserFound } = this.props;
    const params = { "Person.FiscalCode": cf };
    // 执行数据库查询
    /* 你的数据库请求代码 */
      .then(response => {
        const utente = response.docs[0];
        onUserFound(utente.Person); // 调用父组件传来的回调,把数据传回去
      })
      .catch(error => console.error("查询失败:", error));
  }

  render() {
    // 这里可以返回加载状态的UI,比如<Text>Loading...</Text>
    return null;
  }
}

export default FindUser;

改造ShowProfile组件

在ShowProfile里渲染FindUser,同时传递查询码和回调函数:

// ShowProfile.js
import React, { Component } from "react";
import FindUser from './FindUser';
// 其他导入...

class ShowProfile extends Component{
  constructor(props) {
    super(props);
    this.state = {
      FirstName: '',
      LastName: ''
    };
    // 绑定回调函数的this指向
    this.handleUserFound = this.handleUserFound.bind(this);
  }

  handleUserFound(userData) {
    // 拿到数据后更新state
    this.setState({
      FirstName: userData.FirstName,
      LastName: userData.LastName
    });
  }

  render() {
    const targetCf = "要查询的用户FiscalCode";
    return (
      <View style={styles.container}>
        {/* 渲染FindUser组件,传递查询参数和回调 */}
        <FindUser cf={targetCf} onUserFound={this.handleUserFound} />
        <KeyboardAwareScrollView>
          <View style={styles.page}>
            <Text style={visualProfilo.text}>Name:</Text>
            <Text style={visualProfilo.text1}>{this.state.FirstName}</Text>
            <Text style={visualProfilo.text}>Surname:</Text>
            <Text style={visualProfilo.text1}>{this.state.LastName}</Text>
            {/* 其他内容 */}
          </View>
        </KeyboardAwareScrollView>
      </View>
    )
  }
}

关键点说明

  1. 避免直接实例化React组件并调用方法:这种方式会脱离React的生命周期管理,难以维护状态。
  2. 利用Promise传递异步数据:数据库查询是异步操作,通过Promise可以方便地在调用方获取结果。
  3. 用setState更新状态:React组件只有通过setState更新状态,才会触发重新渲染,把新数据展示到界面上。

内容的提问来源于stack exchange,提问作者Jack23

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.06 21:08:13