【发布时间】:2021-08-18 23:11:00
【问题描述】:
在下面的代码中,当用户单击“复制到剪贴板”按钮时,我得到了未定义的值。这意味着我正在为el.value 获得未定义的值。我在开发人员工具中看到了响应,它在那里显示了预期的响应。
index.ts
app.get("/getUrl",async(req,res)=>{
res.send("http://s3.backetname.aws/"+req.query.fileName)
}
)
剪贴板.jsx
import React from "react";
//Material UI Modules
import IconButton from "@material-ui/core/IconButton";
import Tooltip from '@material-ui/core/Tooltip';
import LinkIcon from '@material-ui/icons/Link';
//Custom Modules
import PopUpMessageSnackbar from "./PopUpMessageSnackbar";
export default function CopyToClipboard(props) {
const [openNewUpdate, setOpenNewUpdate] = React.useState(false);
const copyLinkToClipboard = () => {
const el = document.createElement('textarea');
el.value = props.getBuildAwsUrl(props.fileName) (*)
document.body.appendChild(el);
el.select();
document.execCommand('copy');
document.body.removeChild(el);
setOpenNewUpdate(true);
}
const hidePopUpMessageSnackbar = () => {
setOpenNewUpdate(false);
}
return (
<div>
<Tooltip title="Copy Link">
<IconButton
aria-label="Copy"
onClick={() => {
gtag('event', 'copylinkclicked', {
'event_category': 'linkclicked'
});
copyLinkToClipboard()
}}
>
<LinkIcon />
</IconButton>
</Tooltip>
<PopUpMessageSnackbar
show={openNewUpdate}
message="Link Copied"
hideNewUpdate={() => hidePopUpMessageSnackbar()} />
</div>
)
}
.....
}
Home.jsx
getBuildAwsUrl(fileName){
fetch(
"http://localhost:8000/getUrl?fileName="+fileName
)
.then(res => res.text()) (**)
.then(text => {
return text
});
<CopyToClipboard
fileName = {props.data.fileName}
getBuildAwsUrl={(fileName)=>this.getBuildAwsUrl(fileName)}
/>
当我调试代码时,一旦 fetch 函数控制完成执行返回到 clipBoard (*) 行并分配 undefined 值。然后再次回到 Home.jsx (**) 行。我想这个是问题
如果我这样做(下面的代码),如果我直接返回值,它工作正常,el.value 分配了预期值。这里我用return 替换了fetch()
getBuildAwsUrl(fileName){
return "http://s3.backetname.aws/"+fileName
}
但我不想这样,它应该从http://localhost:8000/getUrl?fileName=value获取
请帮助我...提前致谢
【问题讨论】:
标签: javascript node.js reactjs api express