简体   繁体   中英

React - Managing UI State

I'm creating an UI component, which should be able to maintain its own UI state, but receives data from a parent component via props. This is a common scenario, so what would be considered a best practice?

Example: A directory tree component. The component receives its structure and text content from parent component via props. However, the tree component should manage the visibility status of the nodes by itself (closed/expanded). Should I copy props to state when they are received/updated, and add visibility data there? I'm under impression that initializing state from props is a bad practice.

Maybe something like this?

https://gist.github.com/acro5piano/4945264cfb0a83b681822332ef351ece

You do not need to copy props to local state in such case :)

If you have to modify or convert your prop data, try computed property instead:

get someValueFromProps() {
  return this.props.value.replace('foo', 'bar')
}

The less local state, the better component, as state creates bugs unless programmers pay attention to them.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM