首页 > 解决方案 > 在 react native 中导航时如何从另一个组件调用函数?

问题描述

我想做的事

Refresh从第三到第一导航时,我想在第一中使用函数。

一流的

export default class First extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      items: [],
      checkedItems: [],
    };
  }

  Refresh = async () => {
    const querySnapshot = await DB.getAllItems();

    const items = [];
    querySnapshot.forEach(doc => {
      items.push(doc.data());
    });
    this.setState({
      items,
      checkedItems: [],
    });
  }
}

它从 First 导航到 Second。

二等

export default class Second extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      isModalVisible: false,
    };
  }

  toggleModal = () => {
    this.setState({ isModalVisible: !this.state.isModalVisible });
  }

  render() {
    return (
      <Modal isVisible={this.state.isModalVisible}>
        <Third nav={this} />
      </Modal>
    )
  }
}

Second 有一个子组件,Third 是一个模态组件。

三等

export default class Third extends React.Component {
  constructor(props) {
    super(props);
    this.state = {};
  }

  navigateFirst = () => {
    this.props.nav.toggleModal();
    this.props.nav.props.navigation.navigate('First');
  }

  render() {
    return (
      <View>
        <TouchableOpacity
          onPress={this.navigateFirst}
        >
          <Text>Back To First</Text>
        </TouchableOpacity>
      </View>
    );
  }
}

第三,它导航回第一个关闭模式。

问题

我不想使用componentDidUpdate,因为 First 有复选框。

如果我使用componentDidUpdate,每次按下复选框时,都会触发Refresh

那是我避免的。

如果您能给我任何建议,我将不胜感激。

标签: reactjsreact-native

解决方案


如果每次加载 First.js 时调用 Refresh 函数会更容易吗?然后当你从第三回到第一时,它会自动触发它。

// First.js

componentDidMount() {
  this.Refresh();
  this.props.navigation.addListener('willFocus', this.Refresh)

}

推荐阅读