将数据从Node JS服务器发送到React JS组件

时间:2018-09-11 04:16:30

标签: node.js reactjs

import React, { Component } from 'react';  
class FileList extends Component { 
 constructor(props) { 
  super(props); 
  this.state = { results: null }; 
 }  
 componentDidMount() { 
  const data = new FormData(); 
  fetch('http://localhost:4000/profile',{    method: 'POST',   body : data })   
  .then(     (response) => { 
  console.log("response");        
  console.log(response);         
  response.json().then((result)=>this.setState({ results: results }))      
 } // if the response is a JSON object   )
 .catch(   error => null // Handle the error response object )      }   
 render() {
  return (   <div className="Files">   
  <div>File content: {this.state.results}</div> 
 </div>   );   
 } 
} 
export default FileList;

仍然存在相同的问题,即组件中未显示任何数据,并且未定义警告结果。

3 个答案:

答案 0 :(得分:0)

您应使用JSON.stringify()在react组件中显示json的内容。

例如:

<div>File content: {JSON.stringify(this.state.results)}</div>

答案 1 :(得分:0)

this.setState超出范围。 请尝试以下操作:

  fetch('http://localhost:4000/profile', { method: 'POST', body : data })   
    .then( (response) => { 
      console.log("response");        
      console.log(response);
      let cmpt = this;        
      response.json().then((result) => cmpt.setState({ results: result }));      
    } // if the response is a JSON object   )
    .catch( error => null )

这是将其范围存储在cmpt中,当您使用response.json().then(...)时,它在cmpt内具有正确的范围。

更清洁的解决方案可能是编写一个单独的函数来解析数据,然后从该函数中键入setState

答案 2 :(得分:0)

您为this.setState({results:results})设置了错误的结果参数,应该是这样的this.setState({results:result}),这就是为什么它给您“ 警告:结果未定义。仍然无法正常工作的原因。然后还检查您的后端。 希望对您有帮助。

相关问题