get promise value in react component

前端 未结 2 881
面向向阳花
面向向阳花 2020-12-31 09:58

I have a helper function in my component. When I console.log(helperFunction()) it, I get this in the console.

When I try to add the helper func

2条回答
  •  囚心锁ツ
    2020-12-31 10:08

    When dealing with a value that the render method will be using and is also retrieved asynchronously you should be having that value exist in the state of the component and take advantage of the componentDidMount lifecycle method to retrieve the value.

    class SomeComponent extends React.component {
      constructor() {
        super();
    
        this.state = {
          projectName: ''
        }
      }
    
      componentDidMount() {
        // fetch the project name, once it retrieves resolve the promsie and update the state. 
        this.getProjectName().then(result => this.setState({
          projectName: result
        }))
      }
    
      getProjectName() {
        // replace with whatever your api logic is.
        return api.call.something()
      }
    
    
      render() {
    
        return (
          
        )
      }
     }
    

    you don't want to call the function and resolve the promise in the render method because render method should be a pure function based on state and props. This is a base example but should give you an idea of what needs to change. Just need to set projectName as a state variable and make and resolve the promise in the componentDidMount on the first render it will equal an empty string, once it comes back it will update to whatever the api returns.

    If you don't want to show the input until the api call resolves then you can just add additional checks to see if this.state.projectName equals anything and if so render the input.

提交回复
热议问题