繁体   English   中英

使用 Axios 获取时,如何使用 ReactJs 中的 history.push 将数据数组传递给一个组件到另一个组件

[英]How to pass an array of data to one component to another component using history.push in ReactJs when fetched using Axios

在使用 history.push() 路由页面时,我试图将一些获取的数据传递给另一个组件,但据我所知,由于一些异步/同步问题,它没有通过。 如何解决这个问题

这是数据获取(使用 Axios)和数据传递组件

import React, {useState} from 'react'
import {analyse} from '../../services/dataFetching';

function testFunction() {
    const [data, setData] = useState([]);

    const fetch = () =>{
       
        analyse() // this the axios based function which is defined in the service class
        .then(response => {
            setData(response)})

        .then(
                history.push({ 
                pathname: '/somepage',
                state:data}))

        .catch(error =>{
            console.log(error) })};

    return (
        <div> <button onClick={fetch}>FETCH DATA</button> </div>
    )
}

export default testFunction

在上面的 class 中,它正在获取数据并且可以在控制台中记录。

这里是数据接收子组件

import React from 'react';
import { useLocation } from "react-router-dom";

function testFunction2() {
    const { state } = useLocation();
    console.log("state: ", state) 

    return (
        <div>
            {state}
        </div>
    )
}

export default testFunction2

到这里它总是收到一个空数组

这是因为 useState 调用返回的 function 没有返回 promise,即)setData 不是 promise,所以它立即被解决了。立即调用而不等待 setData() 完成执行。 您在这里要做的是在设置 state 后执行 history.push(),这可以使用 useEffect() 挂钩来完成。

import React, {useState, useEffect} from 'react'
import {analyse} from '../../services/dataFetching';

function testFunction() {
    const [data, setData] = useState([]);
    useEffect(()=>{
    history.push({ 
                pathname: '/somepage',
                state:data})
    },[data])

    const fetch = () =>{
       
        analyse() // this the axios based function which is defined in the service class
        .then(response => {
            setData(response)})

        .catch(error =>{
            console.log(error) })};

    return (
        <div> <button onClick={fetch}>FETCH DATA</button> </div>
    )
}

export default testFunction

现在,只要修改了数据变量,就会调用 useEffect 挂钩中指定的 function,这发生在成功设置 state 时。

暂无
暂无

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

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