2017-06-20 85 views
0

下午好,React-Redux由於狀態可能變化而導致無限循環

在我的課PageList中,我想添加一個函數來改變點擊狀態。然而,當我將這個函數插入一個甚至沒有點擊的按鈕時,瀏覽器就會啓動一個永無止境的循環來改變當前頁面的狀態。

即使我已閱讀有關組件的文檔,這似乎是奇怪的行爲。點擊addPage按鈕時,行爲會發生。

在此先感謝!

分頁:

import React, {Component} from 'react'; 
import {bindActionCreators} from 'redux'; 
import {connect} from 'react-redux'; 
import Page from '../components/Page.jsx'; 
import {addPage} from '../actions/addPage.js' 
import {nextPage} from '../actions/nextPage.js' 
import RaisedButton from 'material-ui/RaisedButton'; 
import _ from 'lodash'; 

class PageList extends Component { 
    constructor(props){ 
    super(props); 
    this.state = { 
     currentpage : 0, 
    }; 
    } 

    nextPage(){ 
    this.setState({currentpage: this.state.currentpage+1}); 
    } 

    renderList() { 
    if(this.props.item){ 
     return (
     <div> 
      <RaisedButton label="Next Page" onClick={this.nextPage()}></RaisedButton> 
      <Page key={this.state.currentpage} index={this.state.currentpage}> 
      {this.props.item.title} 
      {this.props.item.desc} 
      </Page> 
     </div> 
    ); 
    }else{ 
     return(
     <p>No Pages</p> 
    ) 
    } 
    } 

    render() { 
     return (
      <div> 
      <RaisedButton label="Add new Page" onClick={() => this.props.addPage("Titel Page", "Page Beschrijving")}></RaisedButton> 
      <ul> 
       {this.renderList()} 
      </ul> 
      </div> 
     ); 
    } 
} 

// Get apps state and pass it as props to PageList 
//  > whenever state changes, the PageList will automatically re-render 
function mapStateToProps(state, ownProps) { 
    return { 
     pageList: state.pageList, 
     item: _.find(state.pages, 'id', ownProps.currentpage) 
    }; 
} 

// Get actions and pass them as props to to PageList 
//  > now PageList has this.props.selectPage 
function matchDispatchToProps(dispatch){ 
    return bindActionCreators({addPage: addPage, nextPage: nextPage}, dispatch); 
} 

// We don't want to return the plain PageList (component) anymore, we want to return the smart Container 
//  > PageList is now aware of state and actions 
export default connect(mapStateToProps, matchDispatchToProps)(PageList); 
+0

非常感謝這是一個很好的閱讀,我想知道爲什麼發生這種情況,不幸我一直忽略了錯誤。 – Conroyd

回答

0

你呼籲各nextPage功能呈現,而不是將它傳遞給的onClick。

變化onClick={this.nextPage()}onClick={() => this.nextPage()}

+0

非常感謝!我只注意到我也可以使用onClick = {this.nextPage}。那就是我之前使用的,但我沒有注意到它沒有這些:'()' – Conroyd

0

有一個小錯誤:

<RaisedButton label="Next Page" onClick={this.nextPage}> 
</RaisedButton> 

否則this.nextPage()被調用權當它被渲染。