将状态作为属性传递给子组件

3
正如标题所言,我该如何将状态数据传递给一个新的组件。我有一个从IndexedDb加载一些数据的父类。 我将“image”信息作为属性传递给我的子组件。
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} />);
}}

在我的子组件中,我将使用prop来发出新的请求以检索图像。问题在于componentWillMount方法中的prop为空。

interface IImageProps {
image: string;
}

Class Child extends Component<IImageProps> {
constructor(props: IImageProps) {
    super(props);
}

public componentWillMount() {
    console.log("image", this.props.image); // <-- it's allways empty
    // do some async stuff
}

public render() {
    console.log("image", this.props.image); // <-- the image information is shown
}}

我错过了什么?因为在render方法中我可以使用prop吗?我如何正确传递变量?


你正在使用React 16吗? - Joshua Underwood
该项目使用React 16.4构建。 - om_kha
2个回答

阿里云服务器只需要99元/年,新老用户同享,点击查看详情
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));
}

0

由于您的loadData函数是异步的,当Child组件被挂载时,data.image将为空字符串。

例如,您可以等待请求完成后再渲染Child组件。

示例

class Parent extends Component<Props> {
  constructor(props: Props) {
    super(props);

    this.state = {
      data: {
        image: null
      }
    };
  }

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

  public render() {
    const { data }: any = this.stat;

    if (data.image === null) {
      return null;
    }

    return <Child image={data.image} />;
  }
}

你假设在父组件渲染子组件时,图片数据还未加载完成。我认为他更多的是假设在父组件中已经存在数据,但是这些数据无法传递到子组件。如果他使用的是 React 16,则 render 方法的异步特性更有可能导致此问题,componentWillMount 不再安全可靠。此时无法保证组件已经具备了 props 或 context。 - Joshua Underwood
@JoshuaUnderwood 在这种情况下,componentWillMount不是问题,因为在早期版本中,componentWillMount只允许您同步更改状态,而不是异步。 - Tholle

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,