如何在React中将异步道具从父组件传递到子组件

问题描述 投票:0回答:1

想象一下下面这个在React中的简单场景:

enter image description here

在此示例中,我们有一个父级组件和一个子级组件。当父组件开始实例化时,它需要发出一个获取childId的请求。该请求可能是异步的,也可能是异步的。在我的特定情况下,我正在使用电子。

After父id检索childId,然后我想将该childId作为道具传递给子组件,该子组件随后提出另一个请求以检索其自身的状态。

这是我想要实现的功能。在过去的几个小时里,我一直在努力解决的问题涉及到childId的检索。不幸的是,React在父组件检索childId之前创建了子组件。因此,子组件无法检索其自身的状态。

我想看看是否有一种方法可以延迟子组件的渲染,直到父组件检索childId。

ParentComponent

interface IState {
ticketId: number;
}

export class TicketOrchestrator extends React.Component<{}, IState> {
    public state: IState = {
        ticketId:0
    };

public render(): React.ReactNode {
    const onPrevious = () => console.log("FromPrevious");
    const onNext = () => console.log("FromNext");
    return (
    <div> 
        <Ticket ticketId={this.state.ticketId} previous={onPrevious} next={onNext}/>
    </div>
    );
}

public componentDidMount(): void {
    ipcRenderer.on("ticketOrchestrator", this.onMessage);
}

public componentWillUnmount(): void {
    ipcRenderer.removeAllListeners("ticketOrchestrator");
}

private onMessage = (event: any, ticketId: any) => {
    console.log("TicketId", ticketId);
    this.setState({ ticketId: ticketId });
};
}

子组件

interface IState{
    id: number,
    header: {
        ticketNumber: string,
        title: string,
        date: Date
    },
    body: {
        content: string,
    }
}

interface IProps{
    ticketId: number,
    previous: any,
    next: any
}

export class Ticket extends React.Component<IProps, IState> {
    public state:IState = {
        id: this.props.ticketId,
        header: {
            ticketNumber: "",
            title: "",
            date: new Date()
        },
        body: {
            content: "",
        }
    };

public render(): React.ReactNode {
    const handleClickNext = () => this.props.previous();
    const handleClickPrevious = () => this.props.next();
    return (
    <div>
        <button onClick= {handleClickPrevious} >Previous</button>
        <button onClick= {handleClickNext}>Next</button>
        <div>
            <h2>{this.state.header.title}</h2>
            <h4>{this.state.header.date.toLocaleTimeString()}</h4>
        </div>
        <div>
            <p>{this.state.body.content}</p>
            <p>Id: {this.state.id}</p>
        </div>
    </div>
    );
  }
};

谢谢,鲁本

javascript reactjs typescript react-component
1个回答
0
投票
<div> {this.state.ticketId === 0 ? ( <>Loading...</> ) : ( <Ticket ticketId={this.state.ticketId} previous={onPrevious} next={onNext} /> )} </div>;
© www.soinside.com 2019 - 2024. All rights reserved.