[英]ReactJS Update ajax call to child component from onClick method from parent
我有一個從一個json文件傳遞的數據數組。
當我單擊列表項時,它會觸發handleClick
方法,該方法將獲取新的URL並將其設置為提供的狀態。 然后將該狀態傳遞到子組件上,該子組件使用該鏈接進行ajax調用。
問題在於,無論我單擊多少次,ajax調用在組件安裝時僅加載一次,此后不再進行調用。
每當單擊不同的項目時,如何使子組件加載新的網址?
父組件:
getInitialState: function() {
return {
gameUrl: ''
};
},
handleClick: function() {
this.setState({
gameUrl: gameUrl
});
},
render: function() {
var gameList = this.props.data.map(function(game) {
var homeTeamName = game.home_team_name;
var awayTeamName = game.away_team_name;
var gameUrl = game.game_directory+'/anotherFile.json';
console.log(homeTeamName+' vs '+awayTeamName+':'+ gameUrl);
var click = this.handleClick;
return (
<li key={game.location} className="list-group-item" onClick={click}>
{homeTeamName}
</li>
);
}, bind);
return (
<div>
<ul>
{gameList}
</ul>
<GameDetail url={this.state.gameUrl}/>
</div>
);
子組件:
componentDidMount: function() {
$.ajax({
url: this.props.url,
dataType: 'json',
cache: false,
success: function(data) {
this.setState({
data: data.data
});
}.bind(this),
error: function(xhr, status, err) {
console.error(this.props.url, status, err.toString());
}.bind(this)
});
},
實現componentWillReceiveProps
方法。 當道具發生變化且不是初始渲染時將調用它,然后根據現有和即將出現的道具更新狀態。
componentWillReceiveProps: function(nextProps) {
this.setState({
// set something
});
}
感謝@WitVault設法做到了,這是修改后的部分:
我在子組件中將其更改為componentWillReceiveProps,而不是componentDidMount。 確保您要傳遞的道具在子組件和父組件中相同。 (即,在子組件中,道具是url
,在父組件中,您將其傳遞給相同的道具<GameDetail url={this.state.gameUrl}/>
)然后您可以通過nextProps.url
在componentWillReceiveProps
方法中對其進行nextProps.url
componentWillReceiveProps: function(nextProps) {
// Access the url prop
var newUrl = nextProps.url;
$.ajax({
url: newUrl,
dataType: 'json',
cache: false,
success: function(data) {
this.setState({
data: data.data
});
}.bind(this),
error: function(xhr, status, err) {
console.error(this.props.url, status, err.toString());
}.bind(this)
});
},
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.