2016-02-16 59 views
0

我有一個json文件,它是一個數組,存儲包含另一個數組,我想要的另一個字段。我有一個ajax請求,將pitching字段存儲到一個狀態數組中pitchers我有兩個按鈕,單擊它時會傳遞一個等於json文件中team_flag屬性的值。ReactJS從json數據內部陣列設置狀態 - 多個陣列

<button className="btn" onClick={this.handleClick.bind(this, 'home')}>{homeTeamName}</button> 
<button className="btn" onClick={this.handleClick.bind(this, 'away')}>{awayTeamName}</button> 

而且方法:

handleClick: function(teamFlag) { 
    // setState of pitchers to whichever team is clicked (home, away) 
    // this.setState({ pitchers: this.state.pitchers.teamFlag})??? 
    console.log(teamFlag); 
} 

如何設置pitchers狀態,這樣它會採取對應於被點擊的team_flagpitcher陣列? (即如果我點擊homeTeam它將存儲pitcher數組,它是下"team_flag": "home")下面是JSON文件

 "pitching":[ 
     { 
      "pitcher":[ 
       {"name": "Billy", "hand": "right"} 
      ], 
      "team_flag":"away", 
     }, 
     { 
      "pitcher":[ 
       {"name": "Joe", "hand": "right"} 
      ], 
      "team_flag":"home", 
     } 
    ], 

回答

0

假設你擁有整個「投球」的狀態下,pitching鍵你可以東西下陣像:

var pitchers = this.state.pitching.find(function(team) { 
    return team.team_flag === teamFlag; 
}); 

this.setState({ pitchers: pitchers.pitcher }); 

如果只是爲了演示的目的,我不會將結果保存在狀態,而不是我救teamFlag並調用render方法中提到的代碼。

React足夠聰明地知道如果teamFlag或者投球數組發生變化,那麼它需要重新渲染。

編輯:

class YourComponent extends React.Component { 
    constructor(props) { 
     super(props); 
     this.state = { 
      loading: true 
     } 
    } 

    componentWillMount() { 
     // make your ajax request 
     // and when the request is finished 
     this.setState({ loading: true }); 
    } 

    handleClick(ev, flag) { 
     this.setState({ flag: flag }); 
    } 

    render() { 
     let homeTeamName = 'Home'; 
     let awayTeamName = 'Away'; 
     let selectedFlag = this.state.flag; 
     let pitchers = this.state.pitching.find(function(team) { 
      return team.team_flag === selectedFlag; 
     }); 
     return (
      <div> 
       {!this.state.loading ? 
        <div> 
        <button className="btn" onClick={this.handleClick.bind(this, 'home')}>{homeTeamName}</button> 
        <button className="btn" onClick={this.handleClick.bind(this, 'away')}>{awayTeamName}</button> 
        </div>: 
        null 
       } 
       // render using the pitchers array 
      </div> 
     ); 
    } 
}; 
+0

它僅用於展示目的(即我需要獲取裏面的數據'pitcher'並在那裏顯示的數據)。如果上面的代碼沒有進入'handleClick'方法,它將如何知道它被點擊的時間? – Simon

+0

我的不好,我沒有正確表達自己。這個想法是將標誌保存在'handleClick'內的狀態,而不是保存投手。我將用示例組件更新我的答案... – nbermudezs

+1

感謝@nbermudezs,只是想知道什麼會改變加載的狀態,因爲它是真實的整個時間? – Simon