[英]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方法移到componentDidUpdate
或componentDidMount
并进行创建,以便您的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.