2017-01-21 27 views
0

ReactJsには本当に新しく、現在は自分自身のhref値をとり、それを 'action'という関数に渡すonClickイベントを作成するのに苦労しています。Uncaught 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

エラーについては不明である何?変数 'action'は' render'の中にはありません。おかげさまで –

答えて

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:未定義のプロパティ 'action'を読み取ることができません – 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.

関連する問題