React-Redux无限循环,因为可能会改变状态

时间:2017-06-20 14:18:04

标签: javascript 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);

2 个答案:

答案 0 :(得分:0)

您在每个渲染上调用nextPage函数,而不是将其传递给onClick。

使用onClick={this.nextPage()}

更改onClick={() => this.nextPage()}

答案 1 :(得分:0)

有一点错误:

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

否则this.nextPage()在渲染时被调用。