【问题标题】:React - set state using button and pass it as propsReact - 使用按钮设置状态并将其作为道具传递
【发布时间】:2017-08-11 17:53:43
【问题描述】:

我想使用“比较”按钮将比较状态切换为真或假。 接下来我想将这个比较状态作为道具传递给枢轴。

在查看 Toggle 类时,我确实使用了与 react 文档中相同的代码。 https://facebook.github.io/react/docs/handling-events.html 我唯一更改的是要比较的名称 isToggleOn。

查看控制台客户端时,每次组件呈现时都会出现以下错误:

modules.js?hash=5bd264489058b9a37cb27e36f529f99e13f95b78:3941 警告:setState(...):在现有状态转换期间无法更新(例如在render 或其他组件的构造函数中)。渲染方法应该是 props 和 state 的纯函数;构造函数副作用是一种反模式,但可以移动到componentWillMount。`

我的代码如下:

class Dashboard extends Component {
  constructor(props) {
    super(props);
    this.state = { compare: true };

    this.handleClick = this.handleClick.bind(this);
  }

  handleClick(button) {
    if (button === 'compare') {
      this.setState(prevState => ({
        compare: !prevState.compare,
      }));
    }
  }

  render() {
    return (
      <Grid>
        <div className="starter-template">
          <h1>This is the dashboard page.</h1>
          <p className="lead">
            Use this document as a way to quickly start any new project.<br />{' '}
            All you get is this text and a mostly barebones HTML document.
          </p>
        </div>

        <ButtonToolbar>
          <button onClick={this.handleClick('compare')}>
            {this.state.compare ? 'AGGREGATE' : 'COMPARE'}
          </button>
        </ButtonToolbar>

        <PivotTable
          ready={this.props.isReady}
          data={this.props.gapData}
          compare={this.state.compare}
        />
      </Grid>
    );
  }
}

export default (DashboardContainer = createContainer(() => {
  // Do all your reactive data access in this method.
  // Note that this subscription will get cleaned up when your component is unmounted
  const handle = Meteor.subscribe('weekly-dashboard');

  return {
    isReady: handle.ready(),
    gapData: WeeklyDashboard.find({}).fetch(),
  };
}, Dashboard));

关于如何解决这个问题的任何建议?

【问题讨论】:

    标签: javascript reactjs meteor


    【解决方案1】:

    原因就是这一行

    &lt;button onClick={this.handleClick('compare')}&gt;

    这将在执行render 函数时调用handleClick 函数。您可以通过以下方式修复:

    &lt;button onClick={() =&gt; this.handleClick('compare')}&gt;

    或者

    const handleBtnClick = () => this.handleClick('compare');
    
    ...
    <button onClick={this.handleBtnClick}>
    ...

    我更喜欢后者

    【讨论】:

    • 完美运行,我假设您的解决方案仅在单击按钮时执行该功能,而不是在每次呈现时执行。谢谢!
    • Np 我需要等一下。
    猜你喜欢
    • 2018-02-28
    • 1970-01-01
    • 1970-01-01
    • 2023-04-05
    • 2017-04-30
    • 2019-02-20
    • 2021-01-07
    • 2018-02-28
    • 1970-01-01
    相关资源
    最近更新 更多