我've recently started to study reactjs and I'目前正在试验ajax请求并将属性从父级传递给子级 . 我有一个响应组件 Competitions
执行ajax请求:
var Competitions = React.createClass({
getInitialState: function() {
return {
compData: [],
}
},
componentDidMount: function() {
axios.get(this.props.source, {
headers: {'X-Auth-Token': '*******************',
'Content-type': 'application/json'}
})
.then(result => {
this.setState({compData: result.data});
})
.catch(error => {
console.log(error);
});
},
render: function() {
return (
<CompTable compData={this.state.compData} />
);
}
});
module.exports = Competitions;
Competitions
组件将结果数据传递给 CompTable
var CompTable = React.createClass({
propTypes: {
compData: React.PropTypes.array.isRequired
},
handleClick: function(e) {
var url = 'http://api.football-data.org/v1/competitions/x/teams';
var source = url.replace(url.split('/')[5], e);
console.log(source);
},
render: function() {
var list = this.props.compData.map(function (comp, i) {
return (
<tr key={i+1}>
<th scope="row">{i+1}</th>
<td className={comp.id} onClick={this.handleClick.bind(this, comp.id)} >{comp.caption}</td>
</tr>
);
}, this);
return (
<tbody>{list}</tbody>
)
}
});
module.exports = CompTable;
这是 Teams
组件
var Teams = React.createClass({
getInitialState: function() {
return {
teamData: [],
}
},
componentDidMount: function() {
axios.get(this.props.source, {
headers: {'X-Auth-Token': '*******************',
'Content-type': 'application/json'}
})
.then(result => {
this.setState({teamData: result.teams.data});
})
.catch(error => {
console.log(error);
});
},
render: function() {
return (
<TeamsTable teamData={this.state.teamData} />,
);
}
});
module.exports = Teams;
我正在尝试做的是使用handleClick函数单击 CompTable
组件的 compData.id
属性,并将其用作名为 Teams
(与 Competitions
组件相同)的另一个组件的 source
属性,该组件使用给定属性作为源URL为了执行新的ajax请求 . 有没有办法做到这一点?谢谢
1 回答
我想我找到了解决问题的方法 . 所以,
Competitions
是父,CompTable
和Teams
是孩子 . 我不是很完美,我还有其他问题需要解决,但我设法在子组件中使用我在父组件内的第一个ajax调用进行第二次ajax调用,方法是 grabcompData.id
属性并将其传递给子项,单击 . 欢迎任何评论 .Competitions
组件CompTable
组件Teams
组件