如何在发布后正确更新F5显示一个获取

问题描述

我想解释一下我今天遇到的问题。

目前,我在我的数据库中发布一条消息,然后在同一个组件中执行 get 以显示之前发送的数据。

我的问题和下一个我必须手动更新页面显示我的获取, 我想找到一种解决方案,无需按F5直接显示结果

我该如何解决这个问题?谢谢所有

代码腾出空间:)

发布

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
}));
}