简体   繁体   English

反应,我应该从道具设置状态吗?

[英]React, Should I set state from props?

I always use props directly without set it to state and it works just fine, but should I really set state from props and then use that state instead. 我总是直接使用props而不将其设置为state,并且效果很好,但是我应该真正从props设置state,然后使用该状态。 what's the difference? 有什么不同?

Class A extends Component {
    ...some method,
    render() {
      return <>{this.props.message}</>
    }
}

Class A extends Component {
    constructor() {
       super();
       this.state = {
          message: ''
       }
    }
    componentDidMount(){
       this.setState({message: this.props.message})
    }
    render() {
      return <>{this.state.message}</>
    }
}

There really is no need if the values are identical. 如果值相同,则确实没有必要。 Consider that every time you use this.setState() you cause an additional re-render of your component. 考虑到每次使用this.setState()都会导致组件的其他重新渲染。 A small price to pay, but something that can mean much more later on if you have let's say 10000 messages. 付出的代价很小,但是如果您说10000条消息,那以后可能会意味着更多。 So it wouldn't provide any benefit by updating state . 因此,通过更新state不会提供任何好处。 Just use props directly. 只需直接使用道具即可。

It would make some sense to update state if you plan on using the props as an intermediary check. 如果您打算将道具用作中介检查,则更新状态会有些意义。 Let's say you have something like this: 假设您有这样的事情:

class App extends React.Component{
   state = {
     display: none
   }

   componentDidUpdate(){
      if(this.props.data.length > 0){
        this.setState({
           display: true
        })
      }
   }

   render(){
     <div>
       { this.state.display ? "Show value" : "" }
     </div>
   }
}

We can use props to update a state-value that determines if we should display some content. 我们可以使用道具来更新状态值,该状态值确定是否应显示某些内容。

最好使用props中的数据,而无需更新它来声明仅添加2 3行代码和setState函数的额外执行,但是用户不会有任何不同。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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