[英][Redux][Axios][React] Adding redux state inside of a axios / action file
[英]set react state after props get the value from redux state(which is axios request in action and ReduxPromise in Midleware)
我有使用connect函數從redux狀態獲取道具的組件。 但是,當此組件啟動時,我的Redux狀態是ReduxPromise,因此,如果在構造函數中分配this.state = {books:this.props.books},我顯然會出錯。 我試過了
componentWillUpdate(nextProps, nextState){
this.setState({books: nextProps.books});
}
但是在這種情況下,我收到“未捕獲(承諾)RangeError:超出最大調用堆棧大小”,我的瀏覽器凍結了2-3秒,然后才顯示書籍。 在承諾被解決並且this.props.books具有真實值之后,是否可以直接將prop分配給react狀態(我需要它使用過濾器進行操作並將其傳遞給子組件)?
行動:
//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);
超出最大呼叫堆棧大小
這段代碼:
componentWillUpdate(nextProps, nextState){
this.setState({books: nextProps.books});
}
是無限遞歸。 調用this.setState
將調用componentWillUpdate
。
您必須做其他事情。 例如:
shouldComponentUpdate(nextProps, nextState) {
return this.state.books !== nextState.books;
}
componentWillUpdate(nextProps, nextState){
this.setState({books: nextProps.books});
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.