Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
162 views
in Technique[技术] by (71.8m points)

javascript - Object is invalid as react child while trying to use async function

I am trying to add translation system in my app. My sample code:

async translate(txt){
 var res = await translate(txt, {
   //some props
 })

 return res[0] //it was returned as an object, so taking the first element
}

render(){
 return (
   <View>
    <Text>{this.translate('Hello')}</Text>
   </View>
 )
}

I know, async returns a promise but I could not figure out a way to use it in my case.

I have checked other questions, but those didn't work :(

question from:https://stackoverflow.com/questions/65936775/object-is-invalid-as-react-child-while-trying-to-use-async-function

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

You would need to wait for the promise to resolve before displaying the output of translate so you could use a state to store the output once translate finishes.

  constructor() {
    super();
    this.state = {};
  }
  componentDidMount() {
    this.translate("Hello").then((output) => this.setState({ text: output }));
  }
  render() {
    return (
      <View>
        <Text>{this.state.text ? this.state.text : "Loading"}</Text>
      </View>
    );
  }

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...