Warning: file_get_contents(/data/phpspider/zhask/data//catemap/5/ruby-on-rails-4/2.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Javascript 将函数返回值作为道具传递给子组件_Javascript_Reactjs_React Redux - Fatal编程技术网

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

Javascript 将函数返回值作为道具传递给子组件,javascript,reactjs,react-redux,Javascript,Reactjs,React Redux,我有一个子组件在父组件的循环中进行渲染。e、 g.在父组件中,我有: <div className="md-grid"> {images ? images.map((img, index) => ( <PinnedImage key={index} name=

我有一个子组件在父组件的循环中进行渲染。e、 g.在父组件中,我有:

<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>
我希望这个
createImageSrc
的结果通过
imageSRC={this.createImageSrc(img.downlaodURL)}
作为
PROPS
传递给子组件,但我没有得到预期的结果。我做错了什么?我被卡住了。
谢谢

您尝试在渲染方法中使用异步方法

相反,您要做的是将对
createImageSrc
的调用从render方法移动到
componentDidUpdate
componentDidMount
中,并使其在抓取完成时更新状态

下面是您应该执行的操作的伪代码

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>
    );
  }
}
异步函数createImageSrc(url){ const imageSRC=fetch(); 返回图像src; } 类YourComponent扩展React.Component{ 建造师(道具){ 超级(道具); 此.state={ imagesWithSrc:null }; } 组件安装(道具){ 如果(道具图像){ this.fetchImageSrc(props.images); } } fetchImageSrc=(图像)=>{ const promises=images.map((img)=>createImageSrc(img.downloadURL)); 承诺。所有(承诺)。然后(…imageSRCs)=>{ const newImages=images.map((img,idx)=>{ 返回{ …img, imageSRC:imageSRCs[idx] }; }); this.setState({imagesWithSrc:newImages}); }); } render(){ const{imagesWithSrc}=this.state; 返回( {imagesWithSrc ?imagesWithSrc.map((img,索引)=>( )) :null} ); } }
旁注只是想让您知道,您在一些地方拼写了downloadURL错误

问题是子组件不知道承诺何时兑现。您必须告诉子组件何时履行了承诺

如果您使用的是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)
  }

{图像
?images.map((img,index)=>(
))
:null}
异步createImageSrc(url,id){
log('createImageSrc调用',{url})
如果(url){
const downlaodURL=`${PROTOCOL}${url}`
console.log({downlaodURL})
const token=localStorage.getItem('access\u token')
const headers=新头({授权:`Bearer${token}`})
常量选项={
方法:“GET”,
标题,
模式:“cors”,
缓存:“默认”
}
const request=新请求(downlaodURL)
const finalResponse=等待获取(请求、选项)。然后(响应=>{
response.arrayBuffer().then(缓冲区=>{
const base64Flag='data:image/jpeg;base64,'
const imageStr=this.arrayBufferToBase64(缓冲区)
常量imageSRC=base64Flag+imageStr
console.log({imageSRC})
this.props.dispatch({type:“imageLoaded”,有效负载:{src:imageSRC,id:id}})
//返回图像
})
})
console.log({finalResponse})
返回最终响应
}
}
arrayBufferToBase64(缓冲区){
设二进制=“”
常量字节=[].slice.call(新的Uint8Array(缓冲区))
字节数。forEach(b=>{
二进制+=字符串。fromCharCode(b)
})
返回窗口.btoa(二进制)
}
    <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)
  }