用了一天的時(shí)間搞這個(gè)窝革,踩坑不少
class PrizeItems extends Component{
constructor(props){
super(props);
this.state = {
posts: []
};
};
componentWillMount(){
var _this = this;
var p1 = new Promise(function (res, rej) {
$.ajax({
url:"src/data/award.json",
type:"GET",
dataType:"json",
success:function (data) {
res(data);
},
error:function (data) {
rej("請(qǐng)求失敗");
}
})
});
p1.then(function (data) {
console.log(data);
const posts = data.awards.map((obj) => obj);
_this.setState({ posts });
});
}
render(){
console.log(this.state.posts);
return(
<ul>
{this.state.posts.map((post) =>
<PrizeItem key={post.rank.toString()} productName = {post.productInfo.productName} picUrl={post.productInfo.picUrl}>
</PrizeItem>
)}
</ul>
)
}
}
1.state這個(gè)對(duì)象內(nèi)部可以是任意的數(shù)據(jù)類型
2.ajax請(qǐng)求是異步進(jìn)行的,所以數(shù)據(jù)要在 componentWillMount或 componentDidMount生命周期內(nèi)完成沛鸵。
3.componentWillMount 內(nèi)的this與ajax內(nèi)的this不是一樣的批钠,需要進(jìn)行綁定
var _this = this;
_this.setState({ posts });
項(xiàng)目比較大時(shí)晋被,我們可以用redux,以上適用于小型項(xiàng)目哦吱七,哈哈