2017-01-21 35 views
0

我對ReactJs非常陌生,目前正在努力創建一個onClick事件,它將採用自身的href值並將其傳遞給一個名爲'action'的函數。未捕獲(承諾)ReferenceError:<function>未定義

動作函數應該阻止默認的瀏覽器行爲,對傳入的URL執行GET請求,並顯示包含響應和狀態的警報對話框。

但是我堅持試圖與下面的錯誤叫我函數從onClick事件:

Uncaught (in promise) ReferenceError: action is not defined

var Content = React.createClass({ 
    getInitialState: function() { 
     return { 
      teams: [] 
     } 
    }, 

    componentDidMount: function() { 
     const makeRequest =() => axios.get("http://localhost:5000/api/teams").then(({ data }) => this.setState({ teams: data })); 

     this.serverRequest = makeRequest(); 

     this.poll = setInterval(() => { 
      this.serverRequest = makeRequest(); 
     }, 10000) 
    }, 

    componentWillUnmount: function() { 
     this.serverRequest.abort(); 

     clearInterval(this.poll) 
    }, 

    action: function(e) { 
     e.preventDefault(); 

     $.get(e.href, function(res, status) { 
      alert("Response: " + res + "\nStatus: " + status); 
     }); 
    }, 

    render: function() { 
     const { teams } = this.state; 

     return (
      <div className="list-group"> 
       { teams.map(function(team) { 
        return ([ 
         <a href={ "http://localhost:5000/api/teams?name=" + team.name} onClick={ action }>Click Me</a> 
        ]); 
       })} 
      </div> 
     ) 
    } 
}); 

ReactDOM.render(<Content />, document.getElementById('content')); 
+1

有什麼不清楚的錯誤? 'render'中不存在變量'action'。 –

回答

1

嘗試this.action而不是action

UPDATE

我發現這個問題。這完全取決於範圍。您不能訪問map內部的this

render: function() { 
    const { teams } = this.state; 

    return (
     <div className="list-group"> 
      { teams.map((team) => { 
       return ([ 
        <a href={ "http://localhost:5000/api/teams?name=" + team.name} onClick={ this.action }>Click Me</a> 
       ]); 
      })} 
     </div> 
    ) 
} 
+0

謝謝。我試過,並導致:Uncaught(承諾)TypeError:無法讀取未定義的屬性'動作' – cvandal

+0

@cvandal答案已更新。請嘗試。 –

+0

比'that'更好地使用箭頭函數。 –

1

它具有約束力的問題,試試這個它會工作:

render: function() { 
    const { teams } = this.state; 

    return (
     <div className="list-group"> 
      { teams.map((team,i)=>{ 
        return <a key={i} href={ "http://localhost:5000/api/teams?name=" + team.name} onClick={ this.action }>Click Me</a> 
       }) 
      } 
     </div> 
    ) 
} 

建議:每當動態創建HTML元素,始終指定唯一的密鑰每個元素,key價值將您的組件保持唯一確定。

Facebook React Doc

Keys help React identify which items have changed, are added, or are removed. Keys should be given to the elements inside the array to give the elements a stable identity.

相關問題