Welcome to Qi-U Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
338 views
in Technique[技术] by (71.8m points)

react纯函数组件,父组件异步获取数据传递给子组件的问题(子组件拿到的数据是空)

纯函数组件没有生命周期

父组件

import React, { useState, useEffect } from 'react';
import { Button, message } from 'antd';
import List from '../../components/List/List'
import './Exam.scss'
import axios from '../../service/axios';

export default function Exam() {
    let exam =[];
    useEffect(() => {
        axios.post(`url`,{}).then((res) => {
            if (res.success){
                exam = res.result;
                console.log(22222,exam)
            }else{
                message.error(res.message)
            }
        })
    }, [])
    return (
        <div className="test">
            <List list={exam}></List>
        </div>
    );
}

子组件

import React, { useState,useEffect } from 'react';
import { Image } from 'antd';
import { useHistory } from 'react-router-dom';
import "./List.scss";

function ListItem(props) {
    const hisorty = useHistory();
    const i = props.value;
    const handleClick = (i) => {
        hisorty.push(i.path)
    };
    return (
        <div className="block" onClick={() => handleClick(i)}>
            ![]({i.url} style={{ height: )
        </div>
    )
}
export default function List(props) {
//这里获得的props一直是空 如果父组件的数据是写死的 传递过来 就可以拿到 但是如果是axios拿来的 就是空 怀疑是异步的问题 
这种场景下 如何拿到父组件数据
     useEffect(() => {
       console.log(1111,props)
    }, [])
    const numbers = props.list;
    console.log(numbers)
    const listItems = numbers.map((item, index) =>
        <ListItem key={index} value={item} />

    );
    return (
        <ul>
            {listItems}
        </ul>
    );
}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

Please log in or register to answer this question.

1 Answer

0 votes
by (71.8m points)

你在父组件中直接定义了变量,不是通过useState来定义。

const [exam, setExam] = useState([]);
    useEffect(() => {
        axios.post(`url`,{}).then((res) => {
            if (res.success){
               setExam(res.result);
                console.log(22222,exam)
            }else{
                message.error(res.message)
            }
        })
    }, [])

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to Qi-U Community for programmer and developer-Open, Learning and Share
...