我遇到了两个挑战:
- 即使根据 React 指南,不鼓励派生状态,但某些边缘情况仍然需要它。
就带有 React Hook 的功能组件而言,React Hook的等效实现是什么,如果我确实需要在类组件中的派生状态,将在每个父渲染的 componentWillReceiveProps 中更新
见下面的代码示例:
class App extends Component {
constructor(props) {
super(props);
this.state = {
count: props.count > 100 ? 100 : props.count,
}
}
/*What is the equivalent implementation when React Hook is used here componentWillReceiveProps*/
componentWillReceiveProps(nextProps) {
if (nextProps.count !== this.props.count) {
this.setState({
count: nextProps.count > 100 ? 100 : nextProps.count
});
}
}
render() {
return ( <
div > {
this.state.count
} <
/div>
);
}
}
export default App;
至于componentDidUpdate,componentDidUpdate在使用React Hook时有对应的,你必须像这样使用它,
React.useEffect(() => { return () => { }; }, [parentProp]);
useEffect 的第二个参数确保代码仅在 prop 更改时执行,但是如果我想根据多个相应的 props 更改执行相应的任务怎么办?如何使用 useEffect完成它?
见下面的代码示例:
class App extends Component {
/*What is the equivalent implementation when functional component with React Hook is used here */
componentDidUpdate(prevProps, prevState) {
if (prevProps.groupName !== this.props.groupName) {
console.log('Let'
's say, I do want to do some task here only when groupName differs');
} else if (prevProps.companyName !== this.props.companyName) {
console.log('Let'
's say, I do want to do some different task here only when companyName differs');
}
}
render() {
/*for simplicity, render code is ignored*/
return null;
}
}
export default App;