【问题标题】:Child not re rendering when child state changed子状态更改时子不重新渲染
【发布时间】:2023-03-05 03:22:01
【问题描述】:

我在子组件中使用模型,我想通过子状态变量来管理可见性,但是当我点击按钮时(它也在子上),子状态变量更新成功但子渲染函数没有被调用? 请检查我的代码,让我纠正我的错误。

      //Main Parent class
        
        export default class ChatMessageComponent extends Component {
            renderItem = ({ index, item }) => {
                return (
                  <ChatMessageView
                    {...this.props}      
                  />
                )
              };
            }
    
    //ChatMessageView child 
    export default class ChatMessageView extends PureComponent {
    render() {
        return (
          <View style={[styles.container, isMinimize ? { width: screenWidth - scale(20) } : null]}>
                <ChatNoticeView
                  {...this.props}
    
                />
          </View>
        )
      }
    }
    }
    //ChatNoticeView child
    export default class ChatNoticeView extends Component {
constructor(props) {
    super(props);
    this.state = {
      visibleModal: this.props.isVisible
    }
  }
 renderModAL = () => {
    return (
      <Modal
        visible={this.state.visibleModal}
      >
        <RejectReason
        />
      </Modal>
    )
  }
render() {
    return (
      <View style={styles.container}>
    {this.renderModAL()}
      </View>
    )
  }
}

//Model
export default class RejectReason extends Component {
    componentDidMount() {
    }

    render() {
        return (
            <View style={styles.container}>

            </View>
        )
    }
}

【问题讨论】:

标签: react-native model parent-child rerender


【解决方案1】:

这是因为您孩子的功能与单击按钮时不会更新的状态绑定在一起。要么需要使用getderivedstatefromprops 方法来更新状态,要么将可见性与道具绑定。我已经更新了你应该显示模态的子组件。

export default class ChatNoticeView extends Component {
constructor(props) {
    super(props);
    this.state = {
      visibleModal: this.props.isVisible
    }
  }
 renderModAL = () => {
    return (
      <Modal
        visible={this.props.isVisible}
      >
        <RejectReason
        />
      </Modal>
    )
  }

您可以阅读更多关于 getDerivedStateFromProps here

【讨论】:

    猜你喜欢
    • 2021-01-27
    • 2020-06-26
    • 1970-01-01
    • 1970-01-01
    • 2018-06-04
    • 2017-10-04
    • 1970-01-01
    • 1970-01-01
    • 2021-06-29
    相关资源
    最近更新 更多