简体   繁体   English

react中如何获取父函数的返回值给子组件(使用props)

[英]How to get the return value of parent function to child component in react (Using props)

I have created a simple react app using functional components.我使用功能组件创建了一个简单的反应应用程序。 The parent component is 'Sites' while the child is 'View Sites'.父组件是“站点”,而子组件是“查看站点”。 I have this function in my parent (Sites component)我的父母有这个功能(网站组件)

function getSitesDB() {
    ref.onSnapshot((querySnapshot) => {
        const items = [];
        querySnapshot.forEach((doc) => {
            items.push(doc.data());
        }); 
        return items;
    });
}

I want to call this function from my child (view sites) component and get the return value to it.我想从我的子(查看站点)组件中调用此函数并获取它的返回值。 for that I have rendered my child component as this,为此,我将我的子组件渲染为这样,

<Route exact path="/sites">
    <ViewSites getSitesDB={getSitesDB}></ViewSites>
</Route>

And called the function using props from the child component as this,并使用子组件中的道具调用该函数,

useEffect(() => {
    setLoading(true);
    const returnVal = props.getSitesDB();

    setLoading(false);
}, []);

I get this returnVal variable as undefined, but this function calls the parent function properly.我将此 returnVal 变量视为未定义,但此函数正确调用父函数。 Just want to know how to get the return value back.只想知道如何取回返回值。 Please help me as I'm new to react.请帮助我,因为我是新手。

currently, you are not returning anything from the getSitesDB() function, and you can't because you only get access to querySnapshot when the callback is called, you can try returning a promise from getSitesDB() and resolve it with items when the callback is called, something like this:目前,您没有从getSitesDB()函数返回任何内容,而且您不能因为只有在调用回调时才能访问querySnapshot ,所以您可以尝试从getSitesDB()返回一个promise并在回调时使用items解决它被称为,是这样的:

function getSitesDB() {
    return new Promise((resolve, reject)=> {
        ref.onSnapshot((querySnapshot) => {
            const items = [];
            querySnapshot.forEach((doc) => {
            items.push(doc.data());
            }); 
            resolve(items);
        });

    })
}

and then in your useEffect() , chain a .then() to the function like this,然后在你的useEffect()中,将 .then( .then()链接到这样的函数,

useEffect(() => {
    setLoading(true);
    props.getSitesDB().then(returnVal => {
        // set returnVal to some state here so you can use it somewhere else in your component
        // =>> setState(returnVal)
        setLoading(false);
    })
}, []);

I am not sure if it will work fine, because I don't know where that 'onSnapshot' comes from, it looks like it listens for an event and calls the callback each time(may be more than once) some change happens, in that case it might throw an error as promise would've already be resolved on initial call.我不确定它是否能正常工作,因为我不知道“onSnapshot”来自哪里,它看起来像是在监听一个事件并每次(可能不止一次)调用回调,一些变化发生在在这种情况下,它可能会引发错误,因为 promise 已经在初始调用时得到解决。

read more on promises here at mdnmdn阅读更多关于 Promise 的内容

When calling the getSitesDB you should return the items that you got from firestore's onSnapshot function.调用getSitesDB时,您应该返回从 firestore 的onSnapshot函数获得的项目。 the onSnapshot function ignores your return items... onSnapshot函数会忽略您的退货商品...

To fetch the data you should do something like this:要获取数据,您应该执行以下操作:

function getSitesDB() {
  return new Promise((resolve, reject) => {
    const items = [];
    ref.onSnapshot((querySnapshot) => {
      querySnapshot.forEach((doc) => items.push(doc.data()));
      resolve(items);
    });
  });
}

To support unmount on your useEffect you should do something like this:要支持在您的useEffect上卸载,您应该执行以下操作:

useEffect(() => {
  let canceled = false;
  const fetchData = async () => {
    setLoading(true);
    const sitesData = await getSitesDB();
    if (!canceled) {
      setSitesData(sitesData);
      setLoading(false);  
    }
  }

  fetchData();
  return () => {
    canceled = true;
  }
}, [getSitesDB]);

You can achive with many ways.您可以通过多种方式实现。 1 Redux 2 Context API 3 Traditional way (Pass that function as props in Parent Component) 1 Redux 2 上下文 API 3 传统方式(在父组件中将该函数作为道具传递)

When ever you get function as a props in component You can use like below mention way当你在组件中获得作为道具的功能时,你可以使用如下提到的方式

useEffect(() => { const returnValue = props.funtionMentionInParent(); console.log(returnValue) }, []);

Thank you谢谢

In Parent use state to keep the result of function在 Parent 使用状态来保持函数的结果

import React, { useState } from "react";
const [sitesDB, setSitesDB] = useState(null);

Also use setSitesDB(items) to update the value in the state.还使用setSitesDB(items)更新状态中的值。

function getSitesDB() {
    ref.onSnapshot((querySnapshot) => {
        const items = [];
        querySnapshot.forEach((doc) => {
            items.push(doc.data());
        }); 
        setSitesDB(items); // here state is updated
        return items;
    });
}

Then pass the function and the state to the Child然后将函数和状态传递给 Child

<Route exact path="/sites">
    <ViewSites getSitesDB={getSitesDB} sitesDB={sitesDB}></ViewSites>
</Route>

Call the function in Child.调用 Child 中的函数。 And use state sitesDB where you need.并在需要的地方使用状态sitesDB

useEffect(() => {
    setLoading(true);
    props.getSitesDB();

    setLoading(false);
}, []);

console.log(props.sitesDB);

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

相关问题 在反应中使用样式组件时如何在子组件中获取父道具 - How to get parent props in child component when using styled component in react 将函数返回值传递给子组件作为道具 - pass function return value to child component as props 反应:将 2 个道具从子组件传回同一 function 中的父组件 - React: Pass 2 props back to the parent component in the same function from the child 如何使用 React Native 中的 props 将数组从父组件传递到子组件? - How to pass an array from a parent component to child component using props in React Native? 为什么子组件在React中无法通过Axios获得父项的道具 - Why child component didnt get parent's props with Axios in React React父级组件道具未传递给子级组件 - React parent component props are not passing to child component React:子组件过滤父组件道具 - React: Child Component Filtering Parent Component Props 如何通过异步函数设置反应父组件状态,然后将此状态作为props传递给子组件? - how to set react parent component state by a async function and then pass this state to child as props? 父母如何改变反应中子组件的道具? - How can a parent alter props for a child component in react? React 父组件道具无法在子组件中使用 forwardRef 道具访问 - React parent component props can't access using forwardRef props in child component
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM