3 回答

TA貢獻1893條經驗 獲得超10個贊
我找到了解決這個問題的方法,方法是使用組件將接收道具并使用即將到來的道具設置我的狀態(tài),并且在渲染中你需要做條件來渲染選擇菜單只有當 state.length !== 0
我發(fā)布了這個答案以防萬一有人遇到同樣的問題我知道它不是最佳解決方案但它對我有用

TA貢獻1796條經驗 獲得超7個贊
componentWillReceiveProps在安裝期間不會被調用。
React 在安裝期間不會使用初始道具調用 UNSAFE_componentWillReceiveProps()。如果某些組件的道具可能會更新,它只會調用此方法。( https://reactjs.org/docs/react-component.html#unsafe_componentwillreceiveprops )
此外,componentWillReceiveProps已棄用并將在 React 17 中刪除。getDerivedStateFromProps改為查看,尤其是關于何時不需要它的注釋。
我相信在您的情況下使用構造函數會非常好,例如:
class Components extends React.Component {
constructor(props) {
super(props)
this.state = { some_property: props.defaultValue }
}
}

TA貢獻1818條經驗 獲得超3個贊
對之前的解決方案感到抱歉,但它不是最佳的我找到了一種方法讓它工作所以你必須將它作為值道具而不是默認值,如果你想將刪除和添加的值捕獲到你的默認值這個函數將幫助你很多
onChange = (e) => {
if (e === null) {
e = [];
}
this.setState({
equipments: e,
});
let added = e.filter((elm) => !this.state.equipments.includes(elm));
if (added[0]) {
let data = this.state.deletedEquipments.filter(
(elm) => elm !== added[0].label
);
this.setState({
deletedEquipments: data,
});
}
let Equipments = e.map((elm) => elm.label);
let newEquipments = Equipments.filter(
(elm) => !this.state.fixed.includes(elm)
);
this.setState({
newEquipments: newEquipments,
});
let difference = this.state.equipments.filter((elm) => !e.includes(elm));
if (difference.length !== 0) {
if (
!this.state.deletedEquipments.includes(difference[0].label) &&
this.state.fixed.includes(difference[0].label)
) {
this.setState({
deletedEquipments: [
...this.state.deletedEquipments,
difference[0].label,
],
});
}
}
};
constructor(props) {
super(props);
this.state = {
equipments: [],
newEquipments: [],
deletedEquipments: [],
};
}
添加回答
舉報