The Problem
Warning: componentWillMount has been renamed, and is not recommended
for use
- Initializing state 初始化狀態
// Before
class AppComponent extends React.Component {
state = {};
componentWillMount() {
this.setState({
selected: this.props.selected,
color: "red"
});
}
}
- Fetching external data 提取外部數據
// Before
class AppComponent extends React.Component {
state = {
data: null,
};
componentWillMount() {
fetch("https://sentry.io/data").then(
res => {
this.setState({data: res.json()});
}
);
}
}
The Solution
從React版本16.3開始,以下組件生命週期方法正在逐步淘汰。
- componentWillMount
- componentWillReceiveProps
- componentWillUpdate
如果要使用這些方法,請在方法前面加上UNSAFE_。 這些方法被認爲是“不安全的”,因爲React團隊期望依賴於這些方法的代碼更有可能在React的未來版本中出現錯誤。
根據代碼的目標,您可以完全將componentWillMount與其他生命週期方法一起使用。
解決方案是將狀態初始化移至構造函數或屬性初始化器,如下所示:
// After
class AppComponent extends React.Component {
state = {
selected: this.props.selected,
color: "red"
};
}
解決方案是將數據獲取移到componentDidMount中:
// After
class AppComponent extends React.Component {
state = {
data: null,
};
componentDidMount() {
fetch("https://sentry.io/data").then(
res => {
this.setState({data: res.json()});
}
);
}
}