gpt4 book ai didi

javascript - React - 使用按钮设置状态并将其作为 Prop 传递

转载 作者:行者123 更新时间:2023-11-29 21:02:50 25 4
gpt4 key购买 nike

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

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

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

modules.js?hash=5bd264489058b9a37cb27e36f529f99e13f95b78:3941 Warning: setState(...): Cannot update during an existing state transition (such as within render or another component's constructor). Render methods should be a pure function of props and state; constructor side-effects are an anti-pattern, but can be moved to 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));

关于如何解决这个问题有什么建议吗?

最佳答案

原因是这一行

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

这将调用 handleClick执行时的功能 render功能。您可以通过以下方式修复:

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

或者

const handleBtnClick = () => this.handleClick('compare');

...
<button onClick={this.handleBtnClick}>
...

我更喜欢后者

关于javascript - React - 使用按钮设置状态并将其作为 Prop 传递,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45641149/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com