React中跳过constructor直接在state用this.props是否合规?求禁用原因
this.props directly without a constructor? Great question! Let's break down whether this approach is recommended, and when you might want to use a constructor instead.
First: Your current approach is valid
The syntax state = { visibility: this.props.visibility } uses class field declarations, a standard ES feature fully supported in modern React setups (and properly transpiled by Babel like your example shows). Under the hood, this code is equivalent to initializing state inside a constructor with super(props) called first—so it works as expected for grabbing initial prop values.
When this approach might cause issues
While it works for initial setup, there are a couple of key scenarios where you’ll need additional logic, or might want to switch to a constructor:
Props updates won’t sync to state automatically
This is the biggest gotcha! Your state is only initialized once when the component is first created. If the parent component passes a newvisibilityprop later, your component’s state won’t update to match it. This can lead to stale state that doesn’t reflect the latest props.If you need state to stay in sync with props, you’ll need to handle updates explicitly with:
componentDidUpdate(for React <16.3):componentDidUpdate(prevProps) { if (prevProps.visibility !== this.props.visibility) { this.setState({ visibility: this.props.visibility }); } }getDerivedStateFromProps(for React 16.3+):static getDerivedStateFromProps(nextProps, prevState) { if (nextProps.visibility !== prevState.visibility) { return { visibility: nextProps.visibility }; } return null; }
Complex initialization logic
If your state requires more than simple prop assignment—like running calculations, parsing data, or binding event handlers—using a constructor makes your code more organized. Constructors are explicitly designed for initialization tasks, so complex logic here is easier to follow for other developers (and future you!).
Do you have to use a constructor?
Nope! React’s official docs explicitly mention that class field declarations are a valid, concise alternative to constructor-based state initialization—as long as you account for prop updates if needed.
Final takeaway
Your current code is fine for simple, one-time initialization from props. Just remember: if the props your state depends on might change later, you need to add logic to sync state with those updates. For complex setup, a constructor is a better home for your initialization code.
内容的提问来源于stack exchange,提问作者Gaurav Soni

