2017-10-17 34 views
0

我在下面有一個反應組件。我想知道是否有任何事情可以改善代碼編寫的方式?我正在努力學習反應,並希望學習如何更好地編寫代碼。謝謝!改善React組件

component.var JSON_URL = "https://api.example.io/comments.json"; 

class CommentList extends React.Component { 
constructor() {  
    super();  
    this.state = { comments: [] } 
       } 
componentDidMount() {  
    $.ajax({  
     url: JSON_URL,  dataType: 'json',  success: function(data) {  this.setState({comments: data.comments});  }.bind(this) }); 
}; 
render() {  
    return <ul> {this.state.comments.map((comment) => {     
     return <li>{comment.body}—{comment.author}</li>;    })}   </ul>; } 
} 
React.render(<CommentList />, document.getElementById('root')) 
+2

https://codereview.stackexchange.com –

+0

第一步是使用換行符和縮進來提高可讀性。 –

+0

你真的需要eslint。使用重組來代替狀態。使用無狀態函數。將ajax請求放入另一個模塊中。 –

回答

0

這段代碼沒有那麼糟,只是需要格式化。這裏有一些小東西,可以提高它:

  • 確保一切正確格式化
  • 提取Ajax請求到它自己的功能(應該是在它自己的模塊也許)
  • 可能是更好的使用不同的Ajax庫比的jQuery(愛可信,取)
  • 擺脫構造的,因爲它沒有被使用,只是直接在類

添加狀態
import React, {Component} from 'react'; 

// move api related things to it's own module 
const JSON_URL = 'https://api.example.io/comments.json'; 
const getComments = (callback) => { 
    $.ajax({ 
    url: JSON_URL, 
    dataType: 'json', 
    success: (data) => { 
     // handle errors 
     callback(data.comments); 
    } 
    }); 
}; 

class CommentList extends Component { 
    state = { 
    comments: [] 
    }; 

    componentDidMount() { 
    getComments(this._setComments); 
    } 

    _setComments = (comments) => { 
    this.setState({ 
     comments 
    }); 
    } 

    render() { 
    return (
     <ul> 
     {this.state.comments.map((comment) => { 
      return (
      <li> 
       {comment.body}—{comment.author} 
      </li> 
     ); 
     })} 
     </ul> 
    ); 
    } 
} 

ReactDOM.render(
    <CommentList />, 
    document.getElementById('root') 
); 
+0

'可能會比jquery(axios,fetch)更好地使用不同的ajax庫' 除非他將jQuery用於超過ajax請求,否則它不會。 –

+0

上午好奇,爲什麼使用不同的庫會更好?我明白,jQuery的構建意圖是操縱DOM,這與虛擬DOM和ReactJS的想法相反,在這種想法中可能會出現意想不到的錯誤。請指教。 @MartinDawson – fungusanthrax

+1

MartinDawson是真的。 @fungusanthrax大多數反應應用程序不會使用jQuery。關於如何使用jQuery來做Ajax並沒有什麼不好的地方,只是如果你只使用ajax部分,那麼這是一個很大的開銷。此外承諾往往更容易處理,所以很高興使用更現代化的ajax庫。這並不重要,只是一個建議。 –

0

一般情況下,這裏看起來很有用。 @Felix King在可讀性方面是正確的 - 格式化你的代碼使批評變得更容易。我馬上注意到的一件事是您代碼中的最後一次調用是React.render(<CommentList />, document.getElementById('root')),但.render方法僅在ReactDOM API中公開。此外,請務必在代碼示例的頂部包含您的import,這樣可以更輕鬆地找出本地定義的內容以及來自其他地方的內容。在componentDidMount()中有您的AJAX請求是現貨。