如何在reac js redux web应用程序中从另一个组件中调用reac函数?

nc1teljy  于 12个月前  发布在  其他
关注(0)|答案(3)|浏览(100)

我有下面的代码,但它给出了错误:

const fetchData = (name) => {
  return async (dispatch) => {
    dispatch(fetchDataRequest());
        
    await axios
      .get(url)
      .then((response) => {
        data = response;
      })
      .catch((error) => {
        data = [];
      });
    return data;
  };
};

组件代码:

import {fetchData} from "../../Actions/userActions"
import {useEffect, useState, forwardRef} from "react";

export const ParentModal = forwardRef((props, ref) => {
  console.log(" type:" + typeof fetchData );
    
  const [initialLoading, setinitialLoading] useState(true);

  useEffect (async () => {
    fetchData("foo").then(async (res) => {
      console.log("result arrived!!!");
    });
  }, []);
    
  return (initialLoading) ? (
    <mui.CircularProgress className="smloader" />
    ReactDOM.createPortal (
    <div>
    <ChildModal
    open={open}
    />
    ....

但它给出了这个错误:
Uncaught(in promise)TypeError:(0,_Serviceworkers_redux_userworkers_WEBPACK_IMPORTED_MODULE_4_fetchData(...).则不是函数
fetchData是对远程API的调用。我想要实现的是,只有在来自远程API的数据到达ParentModal后才呈现ChildModal
请注意,控制台打印:类型:函数
结果来了!!!从未打印。
动作是形实转换动作和归约器。大多数代码被删除,因为实际代码要大得多。只要减少到最低限度就可以解决问题。

4xy9mtcn

4xy9mtcn1#

fetchData函数返回一个形实转换程序(一个返回函数的函数)而不是一个promise。要调用形实转换程序,需要使用dispatch调用它

import { fetchData } from '../../Actions/userActions';

export const ParentModal = hooks.forwardRef((props, ref) => {
  const dispatch = useDispatch();
    
  const [initialLoading, setinitialLoading] = hooks.useState(true);

  hooks.useEffect(() => {
    dispatch(fetchData("foo")).then(() => {
      console.log("result arrived!!!");
      setinitialLoading(false);
    });
  }, [dispatch]);
    
  return (
    <React.Fragment>
      {initialLoading && <mui.CircularProgress className="smloader" />}
      {!initialLoading && ReactDOM.createPortal(
        <ChildModal open={open} />,
        document.getElementById('modal-root')
      )}
    </React.Fragment>
  );
});

ps.在.then()回调中将initialLoading标志设置为false,以便在数据到达后呈现ChildModal
Redux官方文档:https://redux.js.org/advanced/async-actions#async-action-creators

s4chpxco

s4chpxco2#

首先,修改你的fetchData,因为我看到一个不完整的代码或一些语法错误。
修改fetchData函数

// i'll maintain same syntax for easy understanding 
const fetchData = (name) => {
  return async(dispatch) => {
    dispatch(fetchDataRequest());

    try {
      const response = await axios.get(url);
      const data = response.data;
      return data; // return the data from your api if any, to be used when this function is called
    } catch (error) {
      console.error(error);
      return [];
    }
  };
};

1.调用函数并检查是否有任何返回数据

import {
  fetchData
} from "../../Actions/userActions";

export const ParentModal = hooks.forwardRef((props, ref) => {
  const [initialLoading, setInitialLoading] = hooks.useState(true);

  hooks.useEffect(() => {
    fetchData("foo")
      .then((res) => {
        console.log("result arrived!!!");
        console.log({
          res
        }); // this should print the response into your console just so you see what returned from the function 
        setInitialLoading(false); // Set loading to false when data arrives
      })
      .catch((error) => {
        console.error(error);
        setInitialLoading(false); // Handle errors and set loading to false
      });
  }, []);

  return initialLoading ? ( <
    mui.CircularProgress className = "smloader" / >
  ) : (
    ReactDOM.createPortal( <
      div >
      <
      ChildModal open = {
        open
      }
      /> <
      /div>,
      // ...
    )
  );
});
hgc7kmma

hgc7kmma3#

据我所知,fetchData似乎是一个异步操作创建器,例如。一个Thunk动作,因此它需要被 * 分派 * 到商店。在你分享的代码中,你只调用了第一个函数,而不是返回Promise对象的返回函数。
async/await与Promise链混合使用通常也被认为是反模式。使用一个或另一个。
useEffect钩子回调函数也不能是async函数,它必须是常规的同步函数。

const fetchData = (name) => async (dispatch) => {
  dispatch(fetchDataRequest());

  try {
    const { data } = await axios.get(url);
    return data;
  } catch(error) {
    return [];
  };
};
import { useDispatch } from "react-redux";
import { fetchData } from "../../Actions/userActions";

export const ParentModal = forwardRef((props, ref) => {
  const dispatch = useDispatch();

  ...

  useEffect(() => {
    dispatch(fetchData("foo"))
      .then((res) => {
        console.log({ res });
      });
  }, [dispatch]);

  ...

相关问题