将状态作为道具传递给子组件

时间:2018-08-01 16:43:37

标签: reactjs typescript

正如标题所述,如何将状态数据传递给新组件。我有一个父类,它从IndexedDb加载一些数据。

我会将“图像”信息作为道具传递给我的子组件。

float

在我的子组件中,我将使用道具提出一个新请求以获取图像。问题在于componentWillMount方法中的prop为空。

class Parent extends Component<Props> {

constructor(props: Props) {
    super(props);

    // map state to json structure
    this.state = {
        data: {
          image: ''
          [...]
        };
}

public componentWillMount() {
    const dataProvider = new DataProvider(DataProvider.DBNAME);
    dataProvider.loadData('somedoc')
        .then((data: object) => this.setState({data}));
}

public render() {
    const {data}: any = this.stat
    return (<Child image={data.image} />);
}}

我错过了什么,因为在渲染方法中我可以使用道具?如何正确传递变量?

2 个答案:

答案 0 :(得分:2)

感谢您的帮助。我用componentDidUpdate()方法解决了我的问题。如文档https://developmentarc.gitbooks.io/react-indepth/content/life_cycle/update/postrender_with_componentdidupdate.html

中所述

现在我的最终解决方案:

componentDidUpdate() {
    const imageName: string = this.props.imageName;
    const dataProvider = new DataProvider(DataProvider.DBNAME);

    dataProvider.loadImage('somedoc', imageName)
        .then((response: any) => {
            let {imageDataUrl}: any = this.state;
            if (imageDataUrl !== response) {
                imageDataUrl = response;
                this.setState({imageDataUrl});
            }
        })
        .catch((error: any) => console.log(error));
}

答案 1 :(得分:0)

由于您的ipV4Pattern = '^(([0-9]|[1-9][0-9]|1[0-9]{2}|2[0-4][0-9]|25[0-5])\.){3}([0-9]|[1-9][0-9]|1[0-9]{2}|2[0-4][0-9]|25[0-5])$'; 函数是异步的,因此在装入loadData组件时data.image将为空字符串。

您可以例如等待Child组件的呈现,直到请求完成。

示例

Child