简体   繁体   English

将函数返回值传递给子组件作为道具

[英]pass function return value to child component as props

I have a react child component rendering in a loop in parent component. 我在父组件的循环中有一个反应子组件渲染。 eg in parent component I have as such: 例如在父组件中,我有这样的:

<div className="md-grid">
                  {images
                    ? images.map((img, index) => (
                      <PinnedImage
                        key={index}
                        name={img.mediaName}
                        picture={img.downloadURL}
                        imageSRC={this.createImageSrc(img.downlaodURL)}
                        onClick={this.downloadDoc.bind(
                          this,
                          img.downloadURL
                        )}
                      />
                    ))
                    : null}
                </div>

I want to call a function in parent which is authorized fetch request to the file server using REST Endpoint. 我想在父级中调用一个函数,该函数是使用REST端点向文件服务器授权的fetch请求。 I am calling the function on imageSRC props of the child component . 我在child component imageSRC props上调用该函数。 Below are the functions. 以下是功能。

  async createImageSrc (url) {
    console.log('createImageSrc called', { url })
    if (url) {
      const downlaodURL = `${PROTOCOL}${url}`
      console.log({ downlaodURL })
      const token = localStorage.getItem('access_token')
      const headers = new Headers({ Authorization: `Bearer ${token}` })
      const options = {
        method: 'GET',
        headers,
        mode: 'cors',
        cache: 'default'
      }
      const request = new Request(downlaodURL)
      const finalResponse = await fetch(request, options).then(response => {
        response.arrayBuffer().then(buffer => {
          const base64Flag = 'data:image/jpeg;base64,'
          const imageStr = this.arrayBufferToBase64(buffer)
          const imageSRC = base64Flag + imageStr
          console.log({ imageSRC })
          return imageSRC
        })
      })
      console.log({ finalResponse })
      return finalResponse
    }
  }

arrayBufferToBase64 (buffer) {
    let binary = ''
    const bytes = [].slice.call(new Uint8Array(buffer))
    bytes.forEach(b => {
      binary += String.fromCharCode(b)
    })
    return window.btoa(binary)
  }

I wanted the result of this createImageSrc to be pass as PROPS to the child component through imageSRC={this.createImageSrc(img.downlaodURL)} But I am not getting as expected. 我希望将此createImageSrc的结果作为PROPS通过imageSRC={this.createImageSrc(img.downlaodURL)}传递给子组件,但我没有得到预期的结果。 What am I doing wrong? 我究竟做错了什么? I am stuck. 我被困住了。 Thanks 谢谢

You're trying to use an asynchronous method in your render method. 您正在尝试在渲染方法中使用异步方法。

What you want to do is instead move your call to createImageSrc from the render method into either componentDidUpdate or componentDidMount and make it so that your createImageSrc updates the state when fetching is done. 您要做的是将对createImageSrc的调用从render方法移到componentDidUpdatecomponentDidMount并进行创建,以便您的createImageSrc在完成提取后更新状态。

Here is pseudo code of what you should do 这是您应该做什么的伪代码

async function createImageSrc(url) {
  const imageSRC = fetch();
  return imageSRC;
}

class YourComponent extends React.Component {

  constructor(props) {
    super(props);

    this.state = {
      imagesWithSrc: null
    };
  }

  componentDidMount(props) {
    if (props.images) {
      this.fetchImageSrc(props.images);
    }
  }

  fetchImageSrc = (images) => {
    const promises = images.map((img) => createImageSrc(img.downloadURL));
    Promise.all(promises).then((...imageSRCs) => {
      const newImages = images.map((img, idx) => { 
        return {
          ...img,
          imageSRC: imageSRCs[idx]
        };
      });
      this.setState({ imagesWithSrc: newImages });
    });
  }

  render() {
    const { imagesWithSrc } = this.state;
    return (
      <div className="md-grid">
        { imagesWithSrc
           ? imagesWithSrc.map((img, index) => (
              <PinnedImage
                key={index}
                name={img.mediaName}
                picture={img.downloadURL}
                imageSRC={img.imageSRC}
                onClick={this.downloadDoc.bind(
                      this,
                      img.downloadURL
                    )}
              />
            ))
        : null}
      </div>
    );
  }
}

Side note just wanted to let you know that you spelled downloadURL wrong in a few places 旁注只是想让您知道您在某些地方拼写了downloadURL错误

the problem is child component will not know when promise will be fulfilled. 问题是子组件将不知道何时会兑现承诺。 you will have tell child component when promise fulfilled. 当诺言实现时,您将告诉子组件。

if you are using redux add image loaded to store where each child can get its source on re-render. 如果您使用的是redux,则添加加载的图像以存储每个孩子可以在重新渲染时获得其来源的位置。

    <div className="md-grid">
                  {images
                    ? images.map((img, index) => (
                      <PinnedImage
                        key={index}
                        id={index[or some other unique id]}
                        name={img.mediaName}
                        picture={img.downloadURL}
                        imageSRC={this.createImageSrc(img.downlaodURL,id[same id used as child id])}
                        onClick={this.downloadDoc.bind(
                          this,
                          img.downloadURL
                        )}
                      />
                    ))
                    : null}
                </div>


    async createImageSrc (url,id) {
    console.log('createImageSrc called', { url })
    if (url) {
      const downlaodURL = `${PROTOCOL}${url}`
      console.log({ downlaodURL })
      const token = localStorage.getItem('access_token')
      const headers = new Headers({ Authorization: `Bearer ${token}` })
      const options = {
        method: 'GET',
        headers,
        mode: 'cors',
        cache: 'default'
      }
      const request = new Request(downlaodURL)
      const finalResponse = await fetch(request, options).then(response => {
        response.arrayBuffer().then(buffer => {
          const base64Flag = 'data:image/jpeg;base64,'
          const imageStr = this.arrayBufferToBase64(buffer)
          const imageSRC = base64Flag + imageStr
          console.log({ imageSRC })
            this.props.dispatch ({type:"imageLoaded",payload:{src:imageSRC,id:id}})
       //   return imageSRC
        })
      })
      console.log({ finalResponse })
      return finalResponse
    }
  }

arrayBufferToBase64 (buffer) {
    let binary = ''
    const bytes = [].slice.call(new Uint8Array(buffer))
    bytes.forEach(b => {
      binary += String.fromCharCode(b)
    })
    return window.btoa(binary)
  }

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 如何将传递函数作为道具发送给子组件 - How to send pass function as props to child component React:将函数作为道具传递给子组件,在子组件中调用onClick - React: Pass function to child component as props, call onClick in child component 反应:将 function(返回)的结果作为道具传递。 但是子组件接收为未定义? - React: Pass result of function (return) as props. But Child component receives as undefined? 当我将 function 传递给子组件时,ReactJS this.props.* 不是 function - ReactJS this.props.* is not a function when I pass a function to child component react中如何获取父函数的返回值给子组件(使用props) - How to get the return value of parent function to child component in react (Using props) 反应:将 2 个道具从子组件传回同一 function 中的父组件 - React: Pass 2 props back to the parent component in the same function from the child React - 将子值作为道具传递 - React - pass child value as props 如何从Vue组件将props值传递给JS函数 - How to pass a props value to a JS function from Vue component 当我通过 props 从父组件将变量的值传递给子组件时,我收到一个未定义的值 - I receive an undefined value when I pass the value of a variable through props from a parent component to a child component 如何将相同的道具传递给Component中的每个孩子 - How pass the same props to every child in Component
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM