[英]React - set state using button and pass it as props
我想使用“比較”按鈕將比較狀態切換為true或false。 接下來,我想通過此比較狀態來樞轉為道具。
在查看Toggle類時,我實際上使用了與react文檔中相同的代碼。 https://facebook.github.io/react/docs/handling-events.html我唯一更改的是名稱isToggleOn以進行比較。
當查看控制台客戶端時,每次組件渲染時都會出現以下錯誤:
modules.js?hash = 5bd264489058b9a37cb27e36f529f99e13f95b78:3941警告:setState(...):在現有狀態轉換(例如在
render
或其他組件的構造函數中)期間無法更新。 渲染方法應該純粹是道具和狀態的函數; 構造函數的副作用是反模式,但可以將其移至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')}>
這將在執行render
功能時調用handleClick
函數。 您可以通過以下方式解決:
<button onClick={() => this.handleClick('compare')}>
要么
const handleBtnClick = () => this.handleClick('compare'); ... <button onClick={this.handleBtnClick}> ...
我更喜歡后者
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.