我有这个分量称之为fetchSpecificBook
行动的创建者:等待道具进行更新
import React, {Component} from 'react';
import { connect } from 'react-redux';
import { fetchSpecificBook } from '../actions/index';
class Cart extends Component {
constructor(props) {
super(props);
this.renderWishlist = this.renderWishlist.bind(this);
}
renderWishlist(){
var quantity;
var itemID;
var tmp;
var myData = this.props.currentCart;
for (var k=0; k<myData.length; k++){
tmp = myData[k];
quantity = tmp.quantity;
itemID = tmp.itemID;
fetchSpecificBook(itemID);
console.log(this.props.currentBook); // prints undefined
}
}
render() {
return (
<div>
<div>
<h3>Your wishlist</h3>
{this.renderWishlist()}
</div>
</div>
);
}
}
function mapStateToProps(state){
return {
currentCart: state.bookReducer.currentCart,
currentBook: state.bookReducer.currentBook
};
}
export default connect(mapStateToProps, {fetchSpecificBook})(Cart);
fetchSpecificBook行动的创建者是这样的:
export function fetchSpecificBook(id) {
let url = 'http://localhost:3001/specific-book/'+id;
return function (dispatch) {
axios.get(url)
.then(response => {
dispatch({
type: FETCH_BOOK,
payload: response
});
});
}
}
和我的减速器:
import {FETCH_BOOKS} from '../actions/types';
const INITIAL_STATE = { currentBook:[] };
export default function(state = INITIAL_STATE, action) {
switch (action.type) {
case FETCH_BOOK:
return { ...state, currentBook:action.payload };
... other cases
default:
return state;
}
}
所以当我的组件被渲染时,它加载了renderWishlist()
,它调用了fetchSpecificBook
将动作发送给减速器的动作创建器。这里currentBook
得到更新,并在我的组件我可以访问currentBook
感谢mapStateToProps
。
我的问题是:我如何等待,直到currentBook
已更新? 正如你可以从我的评论console.log(this.props.currentBook);
上面的代码看到返回未定义。 我想因为我试图打印this.props.currentBook
,它还没有被reducer更新。
很好的答案!不过,为了您的第二点,我宁愿在'componentDidMount'上使用'fetchSpecificBook',而不是在构造函数中 - 为了好的做法。 –
同意。为清晰起见进行编辑。 – 0xRm