首页 > 解决方案 > React how to re-render a placeholder on button click

问题描述

My app is fetching new data from the server every time a button is clicked. It also loads fresh data when the page is loaded using componentDidMount This is then displayed on my input box placeholder using placeholder={this.state.response}.

I would like to re-render the placeholder content with the updated data from the server.

Home.js

export default class Home extends Component {
  state = {

    response: ''
  };


  componentDidMount() {
    this.callApi()
      .then(res => this.setState({ response: res.chunk }))
      .catch(err => console.log(err));
  }



  callApi = async () => {
    const response = await fetch('/password-api');
    const body = await response.json();

    if (response.status !== 200) throw Error(body.message);

    return body;
  };
  
  render() {
    return (
      <div className="App">
        <Header />

        <Container>
          <Row>
            <Col sm="12" md={{ size: 8, offset: 2 }}>
              <FormGroup>
                <Input className="password-area" type="textarea" name="text" id="exampleText" placeholder={this.state.response}/>
              </FormGroup>
            </Col>
          </Row>
          <Row>
            <Col sm="12" md={{ size: 8, offset: 2 }}>
              <button onClick={this.callApi} id="get-pass-button" className="button">
                Generate Password
              </button>
            </Col>
          </Row>
        </Container>
        <Footer />
      </div>
    );
  }
}

标签: javascriptreactjs

解决方案


The placeholder is bound to this.state.response, hence it will update whenever this particular piece of state is changed. The placeholder reacts to the the state change.

Your componentDidMount() calls callApi() and .then() sets the state using it's return value.

Your onClick does not do anything with the return value ofcallApi(). A solution could look like this.

handleClick = () => {
   this.callApi()
      .then(res => this.setState({ response: res.chunk }))
};

And in your render() method:

<button 
   onClick={this.handleClick} 
    id="get-pass-button" 
    className="button"
>
    Generate Password
</button>

推荐阅读