4 回答
TA贡献1802条经验 获得超5个赞
可能的问题是你没有调用 getTranslate 函数,看起来应该是 getTranslate(); 您还需要在收到数据后更新状态。请参阅我已放置评论以指导解决方案... getTranslate 未返回任何值,并且您调用它的地方不合适...
const getTranslate = () => {
getUrl(props.language, props.text);
const axios = require("axios");
axios.get(function (respone) {
console.log("Here comes response from api call: ", respone);
/// update the variable /state/ prop that you want to bind
return respone.contents.translated;
});
};
然后绑定模板中的值:
return (
<div>
<textarea placeholder="Translated..." value={ the value to bind from state/prop}></textarea>
</div>
)
;
TA贡献1801条经验 获得超8个赞
要调用 getTranslate(),您可以使用钩子生命周期方法 useEffect()。从该函数返回的值可以设置为某种状态并将设置的状态绑定到文本区域值。
import React, { useState, useEffect } from "react";
import Axios from "axios";
const Output = (props) => {
const [output, setOutput] = useState('');
const [url, setUrl] = useState('');
useEffect(()=>{
getTranslate();
})
const getUrl = (language, text) => {
console.log("GetURL ran with: ", language, text);
let url = "";
switch (language) {
case "yoda":
url =
" https://api.funtranslations.com/translate/yoda.json?text=" + text;
break;
case "valyrian":
url =
"https://api.funtranslations.com/translate/valyrian.json?text=" +
text;
break;
case "sith":
url =
"https://api.funtranslations.com/translate/sith.json?text=" + text;
break;
case "shakespeare":
url =
"https://api.funtranslations.com/translate/shakespeare.json?text=" +
text;
break;
case "pirate":
url =
"https://api.funtranslations.com/translate/pirate.json?text=" + text;
break;
case "minion":
url =
"https://api.funtranslations.com/translate/minion.json?text=" + text;
break;
case "lolcat":
url =
"https://api.funtranslations.com/translate/lolcat.json?text=" + text;
break;
case "klingon":
url =
"https://api.funtranslations.com/translate/klingon.json?text=" + text;
break;
case "hacker":
url =
"https://api.funtranslations.com/translate/hacker.json?text=" + text;
break;
case "dothraki":
url =
"https://api.funtranslations.com/translate/dothraki.json?text=" +
text;
break;
default:
break;
}
setUrl(url);
};
const getTranslate = () => {
console.log("From get translate")
getUrl(props.language, props.text);
Axios.get(function (respone) {
console.log("Here comes response from api call: ", respone);
setOutput(respone.contents.translated);
});
};
return (
<div>
<textarea placeholder="Translated..." value={output} onChange={()=>console.log("Testing")}></textarea>
</div>
);
};
export default Output;
TA贡献1757条经验 获得超8个赞
您需要将翻译功能移动到“onChange”功能或“onBlur”功能(如果您希望在用户点击后翻译文本)。此外,您传递给 onChange 和 onBlur 的函数应该管理翻译功能的异步性质。
TA贡献1864条经验 获得超6个赞
您可以使用 useEffect 方法,该方法将在每次道具更改或组件渲染时运行。
useEffect(()=>{
getTranslate();
}, [props])
添加回答
举报