我有一個基于反應類的組件,其中我定義了如下狀態:
class MyReactClass extends React.Component {
constructor(props) {
super(props);
this.state = {
selectedDataPoints: new Set()
};
}
// This method is called dynamically when there is new addition of data
storeData = (metricName, dataPoint) => {
if (this.state.selectedDataPoints.has(dataPoint)) {
this.state.selectedDataPoints.delete(dataPoint);
} else {
this.state.selectedDataPoints.add(dataPoint);
}
};
render () {
return (
<p>{this.state.selectedDataPoints}</p>
);
}
}
請注意,最初,狀態是一個空集,不顯示任何內容。但是當狀態最終被填充時,我在再次旋轉變數時遇到了麻煩。它始終以空集為原始狀態。
uj5u.com熱心網友回復:
如果你想讓組件重新渲染,你必須呼叫 this.setState() - 函式。
uj5u.com熱心網友回復:
您可以使用 componentshouldUpdate 方法讓您的狀態反映出來,并且應該使用 this.state({}) 方法設定狀態。
uj5u.com熱心網友回復:
使用此代碼設定集合的狀態:
export default class Checklist extends React.Component {
constructor(props) {
super(props);
this.state = {
selectedDataPoints: new Set()
}
this.addItem = this.addItem.bind(this);
this.removeItem = this.removeItem.bind(this);
}
addItem(item) {
this.setState(({ selectedDataPoints }) => ({
selectedDataPoints: new Set(selectedDataPoints).add(item)
}));
}
removeItem(item) {
this.setState(({ selectedDataPoints }) => {
const newSelectedDataPoints = new Set(selectedDataPoints);
newSelectedDataPoints.delete(item);
return {
selectedDataPoints: newSelectedDataPoints
};
});
}
getItemCheckedStatus(item) {
return this.state.checkedItems.has(item);
}
// This method is called dynamically when there is new addition of data
storeData = (metricName, dataPoint) => {
if (this.state.selectedDataPoints.has(dataPoint)) {
this.state.selectedDataPoints.removeItem(dataPoint);
} else {
this.state.selectedDataPoints.addItem(dataPoint);
}
};
render () {
return (
<p>{this.state.selectedDataPoints}</p>
);
}
}
轉載請註明出處,本文鏈接:https://www.uj5u.com/shujuku/455680.html
標籤:javascript 反应 打字稿 使用状态
