javascript - 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>
);
}
}
解决方案
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>
推荐阅读
- javascript - 如果存在,JS 按类查找一个元素,否则使用 or 运算符使用其他元素
- .net - 通过代码检查 Mac OS 上的 Internet 连接
- c++ - 数组到指针转换期间的临时实现
- go - 在 GO 中使用常见错误消息将字符串解析为不同类型
- r - 2 个多重响应集之间的频率
- python - 无法将 json.dumps 与 with python 语句一起使用
- android - 如何将android视频播放器从活动过渡到片段?
- python - 如何将 numpy 1D 数组插入 numpy 3D 数组?
- php - 为 php 存储的 .env 文件在哪里
- angular - 如何在 Angular 6 中过滤 FormArray 元素