我有两个嵌套的反应组件:外部和内部.每当我调用Inner的setState时,都会调用内部组件的渲染.此外,每当我调用外部组件的setState时,都会调用外部和内部组件的render函数. 我想区分这两种情
我想区分这两种情况并检测内部组件的渲染.我的内部渲染功能应该根据具体情况而有所不同.我怎样才能做到这一点? 您可以利用componentWillReceiveProps仅在组件接收新道具时调用的事实(请在此处查看: http://busypeoples.github.io/post/react-component-lifecycle/),而不是在调用setState时调用,更重要的是它们甚至不必是与现有道具不同的道具(根据 https://facebook.github.io/react/docs/component-specs.html#updating-componentwillreceiveprops).所以你应该能够做一些事情
componentWillReceiveProps() { this.setState({parentUpdated: true}); } render() { if (this.state.parentUpdated) { // Render one way } else { // Render the other way } }
虽然您还需要在渲染之后以某种方式取消设置,或者只是确保对this.setState的每次调用都包含{parentUpdated:false}.