我想解释一下我今天的问题。
目前,我在数据库中发布了一条消息,然后在同一组件中执行get以显示之前发送的数据。
我的问题和下一个问题我必须手动更新页面以显示我的get,我想找到一个解决方案,直接显示结果,而不必按F5
如何解决此问题?thx所有
为代码腾出空间:(
后
postBack(e,) {
e.preventDefault();
const payload = {
phone: this.state.phone,
total: this.state.total ,
}
axios.post('******', payload)
.then(res => {
if (res.error) {
alert(res.error);
}
}).catch(e => {
console.error(e);
}).finally(() => this.setState({
redirect: true
}));
}
获取
getRandom = async () => {
const res = await axios.get(
'*****'
)
this.setState({ data: res.data })
}
componentDidMount() {
this.getRandom()
}
呈现
render() {
let datas = this.state.data.map(chat => {
return (
<form onSubmit={(e) => this.handleSubmit(e, chat,)}>
<label>
<input type="text" name="name" onChange={this.handleChange} />
</label>
<button type="submit">Envoyer</button>
</form>
<div key={chat.id}>
<div key={chat.id}>
<p> your name is {chat.name} </p>
</div>
</div>
)
})
return (
<div>
{datas}
</div>
)
}
}
您可以在POST请求成功后更新data
状态。代码似乎不完整,但它可能类似于这个
postBack(e,) {
e.preventDefault();
const payload = {
phone: this.state.phone,
total: this.state.total ,
}
axios.post('******', payload)
.then(res => {
if (res.error) {
alert(res.error);
} else { // here should be place to update state
this.setState({ data: payload })
}
}).catch(e => {
console.error(e);
}).finally(() => this.setState({
redirect: true
}));
}