在获取axios
GET请求中的数据后,如何才能使我的组件呈现?
我有以下组件:
class CardPool extends React.Component{
constructor(props){
super(props);
this.state = {
cardListBacklog: [],
};
}
componentWillMount(){
axios.get('/cards').then(function(response){
this.setState({cardListBacklog: response.data});
}.bind(this));
}
render(){
return(
<div class="row">
<Section name="Construction of Component 1 with a huge ass name that wont really fit in the section">
<Column columnName="BACKLOG">
<CardList id="card-list-1" column="0" cardList={this.state.cardListBacklog}/>
</Column>
</Section>
</div>
);
}
}
和
class CardList extends React.Component{
constructor(props){
super(props);
this.state = {
cardList: [],
laneID: this.props.column
}
}
componentWillMount(){
this.setState({
cardList: this.props.cardList,
});
}
render(){
const {connectDropTarget} = this.props;
return connectDropTarget(
<div class={"card-list " + this.addClass()} id={this.props.id}>
{
this.state.cardList ?
this.state.cardList.map((card) => {
return <Card key={card.id} state={card} laneID={this.state.laneID}/>
})
: null
}
</div>
);
}
问题是state
的cardListBacklog
传递给CardList
没有更新,cardList
组件中的CardList
仍然是空的。我究竟做错了什么?可能是因为我使用state
设置props
属性?
当你通过CardPool
电话回复时,你没有机会让axios
组件重新渲染。
修改render
组件的CardPool
函数,如下所示:
return this.state.cardListBacklog.length
? <div class="row">
<Section name="Construction of Component 1 with a huge ass name that wont really fit in the section">
<Column columnName="BACKLOG">
<CardList id="card-list-1" column="0" cardList={this.state.cardListBacklog}/>
</Column>
</Section>
</div>
: null;
This demo演示了准系统实现
componentWillMount
生命周期函数只执行一次,因此,当在axios
请求之后,在父项中可用cardList时,子组件的componentWillMount
已经执行,因此其状态不会更新。设置可直接从props派生的状态也不是一个好主意,你应该从从Child调用的父代传递一个处理程序。
class CardPool extends React.Component{
constructor(props){
super(props);
this.state = {
cardListBacklog: [],
};
}
componentWillMount(){
axios.get('/cards').then(function(response){
this.setState({cardListBacklog: response.data});
}.bind(this));
}
removeCard = (card) => {
//do what you need to update cardListBacklog
}
render(){
return(
<div class="row">
<Section name="Construction of Component 1 with a huge ass name that wont really fit in the section">
<Column columnName="BACKLOG">
<CardList id="card-list-1" column="0" cardList={this.state.cardListBacklog} removeCard={this.removeCard}/>
</Column>
</Section>
</div>
);
}
}
和
class CardList extends React.Component{
constructor(props){
super(props);
this.state = {
cardList: [],
laneID: this.props.column
}
}
render(){
const {connectDropTarget} = this.props;
return connectDropTarget(
<div class={"card-list " + this.addClass()} id={this.props.id}>
{
this.props.cardList.map((card) => {
return <Card key={card.id} state={card} removeCard={() => this.props.removeCard(card)} laneID={this.state.laneID}/>
})
: null
}
</div>
);
}