class App extends React.Component {
constructor(props) {
super(props);
this.state = {
name: this.props.name || 'Anonymous'
}
}
render() {
return (
<p>Hello {this.state.name}</p>
);
}
}
删除状态并通过以下实现使用道具?如果是这样你怎么做的?
getDerivedStateFromProps
或(最好)改为功能组件?
期待建议!
这是一个单行无状态组件:
const App = ({ name }) => <p>Hello {name || 'Anonymous'}</p>
它与您的类具有完全相同的行为