我有了一些过时的事件reactcomponent:
componentWillMount() {
const { applicationStages } = this.props;
if (applicationStages && applicationStages.length > 0) {
this.setState({
appColumnsSorted: this.getSortedAppColumns(someVar),
});
}
}
componentWillReceiveProps(nextProps) {
const {
presets: { sortCriteria: sortBy, customCriteria },
} = nextProps;
const { appColumnsSorted } = this.state;
const sortedColumnsUpdated = this.getSortedAppColumns(
appColumnsSorted,
sortBy,
true
);
this.setState({
appColumnsSorted: sortedColumnsUpdated,
});
}
getSortedAppColumns = (appColumns, sortBy, criticalFirst) => {
//returns object
};
“componentWillMount”基本上是初始化appColumnsSorted。问题是,与V16此事件已经过时了。那么可以将事件我现在可以使用这个?还什么是在这种情况下迁移“componentWillReceiveProps”的方式吗?
什么你使用componentWillMount为可以在构造函数中这样做
componentWillMount() {
const { applicationStages } = this.props;
if (applicationStages && applicationStages.length > 0) {
this.setState({
appColumnsSorted: this.getSortedAppColumns(someVar),
});
}
}
将改变
export default class YourClass extends Component {
constructor(props) {
// keep a separate method just to avoid writing code in constructor for readability
this.state = constructInitialState(props);
}
constructInitialState(props) {
const state={};
//More state handling as required
const { applicationStages } = props;
if (applicationStages && applicationStages.length > 0) {
state.appColumnsSorted = this.getSortedAppColumns(someVar);
}
return state;
}
}
这种方法是稍微好一点,因为getDerivedStateFromProps将被调用之前每个渲染并会浪费计算。
从代码段,为什么你想将其存储在状态不是很明显。如果你将它保存到状态,那么你唯一的办法是使用componentDidUpdate作为由Aaditya THAKKAR对方的回答中提到。这将需要您镜像状态的道具仅用于比较的目的(映射道具状态不是最好的办法,更多关于这个链接https://reactjs.org/blog/2018/06/07/you-probably-dont-need-derived-state.html#anti-pattern-unconditionally-copying-props-to-state)
我会,不过,建议您打电话排序计算方法,并返回其直接呈现结果;这将避免在componentDidUpdate额外的检查,以使第二次。由于我不知道,如果这些道具从终极版即将或者父母做出反应成分,另一种选择是,以避免昂贵的计算在这个类,只是无论从父组件提供正确的值或计算了Redux商店的价值和直接发送最后的道具使用。
ComponentWillReceiveProps可以getDerivedStateFromProps
更换。 getDerivedStateFromProps
是正确调用渲染方法之前调用,无论在初始安装和后续更新。它应该返回一个对象来更新状态。这是一个静态方法,所以this
不能在它里面使用。
因此,你可以不再getDerivedStateToProps引用this.getSortedAppColumns
,您需要为componentDidUpdate生命周期。在这里,我已经崩溃ComponentWillReceiveProps
成getDerivedStateFromProps
和componentDidUpdate
:
static getDerivedStateFromProps(nextProps, prevState) {
const {
presets: { sortCriteria: sortBy },
} = nextProps;
if (sortBy === prevState.sortBy) return null;
return ({ sortBy: nextProps.sortBy });
}
componentDidUpdate(_, prevState) {
const { appColumnsSorted, sortBy } = this.state;
if (sortBy !== prevState.sortBy) {
const sortedColumnsUpdated = this.getSortedAppColumns(
appColumnsSorted,
sortBy,
true
);
this.setState({
appColumnsSorted: sortedColumnsUpdated,
});
}
}