簡體   English   中英

在反應中將 API 調用上的數據從父容器傳遞到子容器

[英]Passing data on an API call from parent to child container in react

我對反應還很陌生,我被困在我覺得微不足道的事情上。 所以我想要做的是我想將數據從父組件傳遞給子組件。 我的代碼看起來像這樣。

getData(key) {
    let { getData } = this.props;

    if (getData.code === "ON") {
        Codeapi(getData._id[0])
        .then(res => console.log("Result is", res)),
        (error => console.log(error));
    }
    return (
        <Dialog
            key={key}
            side="left"
            onImageClick={this.handleClick}>
            <ReactSlick />
            </Dialog>
    );
}

所以基本上我現在只是控制台記錄結果,但我想以某種方式將 res 傳遞給包裝在 Dialog 組件中的 ReactSlick 組件。 我將如何在 ReactSlick 組件中使用 res 數據?

嘗試將存儲在父狀態中的數據作為屬性傳遞給子元素。 從 API 接收數據時更改狀態。 更改父項的數據屬性將傳播到子項。

getData(key) {
    let { getData } = this.props;

    if (getData.code === "ON") {
        Codeapi(getData._id[0])
        .then(res => this.setState({data: res)),
        (error => console.log(error));
    }
    return (
        <Dialog
            key={key}
            side="left"
            onImageClick={this.handleClick}>
            <ReactSlick data={this.state.data} />
            </Dialog>
    );
}

在父組件的構造函數中:

constructor(){
  this.state = {data: null}
}

嘗試使用 async/await 先獲取 res,然后將其傳遞給子組件

async getData(key) {
      let { getData } = this.props;
      let res = null;
      if (getData.code === "ON") {
          try{
            res = await Codeapi(getData._id[0]);
          } catch(e) {
            console.log(e);
          }
      }
      return (
          <Dialog
              key={key}
              side="left"
              onImageClick={this.handleClick}>
              <ReactSlick res/>
              </Dialog>
      );
    }

您可能需要一個有狀態的組件來實現這一點。 將響應保存到狀態,然后從狀態中獲取 res 值以將其傳遞給 Slick 組件。

export class TestComponent extends Component {
  constructor() {
    super();
    this.state = {
      res: null
    };
    this.getData = this.getData.bind(this);
  }

  componentDidMount() {
    this.getData();
  }

  getData() {
    let { getData } = this.props;
    if (getData.code === "ON") {
      Codeapi(getData._id[0])
        .then(res => this.setState({ res })) // saving res to state
        .catch(error => console.log(error)); // use catch for errors from promises
    }
  }

  render() {
    const { res } = this.state;
    return (
      <Dialog
        key={key}
        side="left"
        onImageClick={this.handleClick}>
        <ReactSlick res={res} />
      </Dialog>
    )
  }
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM