首页 > 解决方案 > React GET 方法不呈现最新帖子

问题描述

我在我的项目中使用 rest-api,当我运行代码时,GET 方法有效,但每次我通过 POST 方法添加帖子时,数据都会在数据库中创建,但不会在应用程序中呈现。我必须重新启动应用程序才能看到最新帖子。

这应该是实时聊天应用程序,我不确定我的问题出在后端还是前端。当我取出所有 get 和 post 方法时,它工作正常并且显示新消息已发送。但是,当我从 restapi 数据库中提取数据时,仅在刷新页面时才会呈现消息。

main.js

class MessagePanel extends Component {

    state={
      messages:[],
      usernames:[]
          }


  componentDidMount(){
    
    axios.get('http://localhost:8888/restapi/messages')
    .then(response =>{
      this.setState({messages: response.data.data[0].messages});
      console.log(response)
    })

                 
  }

 sendMessage=(mes)=>{

  const headers = {
    'Content-Type': 'application/json',
    'Accept': 'application/json'
  }

  const data={
    username: this.props.username,
    text: mes
  };

    axios.post('http://localhost:8888/restapi/messages', data,{
      headers: headers
    })
    .then(response=> {

    console.log(response)
  })
  
  
 };


 createUsers(){

  this.setState({usernames: 
  [...this.state.usernames, this.props.username]})
  
 }
 
  render()
  
 { 
 
  
  return (
    <div className="MessagePanel">

      <Layout/>
      <SidePanel users={this.state.usernames} />  
      <DisplayMessages messages={this.state.messages} username={this.props.username} />
      <MessageBox sendMessage={this.sendMessage} username={this.props.username}/>

    </div>
  );}
}

export default MessagePanel;

DisplayMessage.js

class DisplayMessages extends Component {

 //will stop auto scrolling down when you send a message
 componentWillUpdate=()=>{

  const node=ReactDOM.findDOMNode(this)
  this.shouldScrollToBottom = node.scrollTop +node.clientHeight + 100 >= node.scrollHeight


}

//Auto scrolls when some client messages
componentDidUpdate=()=>{
  if(this.shouldScrollToBottom) {
    const node= ReactDOM.findDOMNode(this)
    node.scrollTop=node.scrollHeight

  }

}

  render(){
return (
  <div className="DisplayMessage">
    <div className='message-container'>
      {this.props.messages.map(message => {
          return(

              <Message  key={message.id} text={message.text} username={message.username} />
              


          )
      })}
   </div>
  </div>
);}
}

export default DisplayMessages;

消息.js

const message =(props) => {


  let messageClass = 'message-row';


    if (props.isMyMessage) {
        messageClass += ' you-message';
    } else {
        messageClass += ' other-message';
        
    }

    

        return (
    
      <div className='messageClass'>
        <div className='messagedata'>
          
            <div className='userid'>{props.username}</div>
            <div className='textmessage'>{props.text}</div>
        </div>
      </div>
    
  );
}


export default message;

标签: javascriptreactjsaxiosrest

解决方案


您从数据库中提取数据的唯一时间是调用 componentDidMount。我建议您查看 react docs 以了解 componentDidMount 作为 react https://reactjs.org/docs/state-and-lifecycle.html的重要组成部分 您当前的反应应用程序不了解更改后的任何数据库更改在 componentDidMount 期间首先获取数据(主要是在组件首次加载时)。

根据您希望接收消息的“实时”程度,您可以执行诸如每隔几秒轮询 API 以检查更改的更改。这可以通过在 componentDidMount 中创建一个每隔 x 秒获取 API 的计时器来完成,然后您可以在 componentWillUnmount 中进行状态更改。

如果您想要一个更“实时”的解决方案,可能值得研究 websockets,但这需要大量的后端更改。


推荐阅读