【发布时间】:2021-03-08 16:24:36
【问题描述】:
我正在尝试动态翻译一些文本以在用户单击翻译按钮时显示,但我无法将我的值保存在 Promise 之外。我对 Promise 的工作并不多,每个示例只显示 console.log,而不是在 Promise 之外保存值。我真的不明白它们是如何工作的。这是(大部分)我要修复的代码:
constructor(props) {
super(props);
this.state = {
dynamicTranslate: this.props.dynamicTranslate,
};
}
// I've tried this method as both sync and async (with await) but neither work
googleTranslate = (key) => {
const translator = TranslatorFactory.createTranslator();
// translate returns a Promise
return translator.translate(key, i18n.locale)
.then((response) => {return response});
}
renderText() {
// getting some values....
// this loops through all the feedback information
for (var i = 0; i < components_feedback.length; i++) {
let label = (some string);
let value = (some string);
// to do: call google translate call here if Boolean(this.state.dynamicTranslate)
if (Boolean(this.state.dynamicTranslate)) {
// I am ultimately trying to save the translation string from googleTranslate()
// in label/value so I can push it into feedbacks
label = this.googleTranslate(label);
value = this.googleTranslate(value);
}
feedbacks.push({label: label, value: value, type: comp.type})
}
return (
// some stuff
feedbacks.map((feedback, index)) => {
// some stuff
<Text>{feedback.label}</Text>
<Text>{feedback.value}</Text>
// some other stuff
});
);
}
render() {
return (
<View>{this.renderText()}</View>
);
}
我遇到的一个问题是,如果打开翻译,标签/值是一个 Promise。如果我尝试使 renderText() 成为异步方法,它也会变成一个 render() 无法处理的 Promise。不知道从这里去哪里。
【问题讨论】:
-
你需要在你的 render() 中返回。
-
刚刚对其进行了编辑以解决该问题,但这不是问题。我只是在解释我的代码时忘记在其中添加它。
标签: react-native promise async-await state rendering