我有使用connect函数从redux状态获取props的组件 . 但是,当此组件启动时,我的Redux状态是ReduxPromise,所以如果我在构造函数中指定this.state = {books:this.props.books},我显然会收到错误 . 我试过了
componentWillUpdate(nextProps, nextState){
this.setState({books: nextProps.books});
}
但在这种情况下,我得到“未捕获(承诺)RangeError:超出最大调用堆栈大小”,我的浏览器冻结2-3秒,然后才显示书籍 . 在解决了promise并且this.props.books有实际 Value 之后,我是否可以直接将反应状态分配给反应状态(我需要使用过滤器进行操作并将其传递给子组件)?
行动:
//get all books from server
export function getBooksData() {
const request = axios.get(`${ROOT_URL}/db/`);
return{
type: GET_BOOKS,
payload: request
}
}
减速器:
const INITIAL_STATE = { all: [] };
export default function(state = INITIAL_STATE, action){
switch (action.type){
case GET_BOOKS:
return {...state, all: action.payload.data};
}
return state;
}
零件:
class BooksIndex extends Component{
constructor(props){
super(props);
/* getting list of books with the action creator */
this.props.getBooksData();
this.state = {books: this.props.books};
//if filters change state parent component should update the RenderBooks props
//filter state, needed to update component on filter update
var handleToUpdate = this.handleToUpdate.bind(this);
this.state = {filterSwitcher: true};
}
componentWillUpdate(nextProps, nextState){
this.setState({books: nextProps.books});
}
handleToUpdate(someArg){
this.setState({filterSwitcher: someArg});
this.setState({books: this.props.books});
console.log(this.props.books);
}
render(){
return(
<div className="row">
{/* sortig component */}
<SortFilters handleToUpdate = {this.handleToUpdate.bind(this)}></SortFilters>
{ this.state.books == undefined ? <Preloader /> : <RenderBooks books={this.state.books} />}
</div>
)
}
}
function mapStateToProps(state){
return {
books: state.books.all.books
}
}
export default connect(mapStateToProps, {getBooksData})(BooksIndex);
1 回答
这段代码:
是无限递归 . 调用
this.setState
将调用componentWillUpdate
.你必须做点别的事 . 例如: