【问题标题】:React native reload child component反应原生重新加载子组件
【发布时间】:2019-07-18 21:07:18
【问题描述】:

我有 2 个屏幕 A 和屏幕 B。屏幕 A 有一个子组件 SomeList 加载数据,我只是将操作传递给子组件,其余部分由它完成。目前通过 react-navigation 的设计,重新访问时没有操作.我用谷歌搜索并遇到了https://reactnavigation.org/docs/en/navigation-events.html,但不确定当我从 ScreenB 导航到 ScreenA 时如何使用它来重新加载 SomeList。

屏幕A

class ScreenA extends Component {

   render() {
    return (
      <SomeList
        loadData={this.props.actions.getAlllist}
      />
    )
}

屏幕B

Class ScreenB extends Component {

    someAction = () => {
       this.props.navigation.navigate("ScreenA")
    }
}

【问题讨论】:

  • 如果我错了,请纠正我,当您在屏幕 A 中时,您想要的是在 &lt;SomeList/&gt; 组件上加载数据,但是当您导航到屏幕 B 然后返回屏幕 A 时,您希望能够加载新数据吗?
  • @CarlosAbraham 是的先生

标签: react-native react-redux react-navigation react-native-navigation


【解决方案1】:

由于 react-native 的设计,我认为您最好将数据传递给您的子组件。

您可以这样做:

   class ScreenA extends Component {
       constructor(props) {
          super(props)
          this.state = {
            data: [],
          }
          this.props.navigation.addListener('didFocus', this.load)
          this.props.navigation.addListener('willBlur', this.unmount)
        }

       load = ()=>{
          const _data = this.props.actions.getAlllist;
          this.setState({data:_data})
       }
       unmount = ()=>{
          this.setState({data:[]})
       }
       render() {
        return (
          <SomeList
            dataArray ={this.state.data}
          />
        )
    }

};

【讨论】:

    【解决方案2】:

    如果你想在每次渲染时获取数据,你可以使用 componentDidMount 生命周期方法

    class ScreenA extends Component {
       state = {
         data: [];
       }
    
       componentDidMount() {
         this.setState({ data: this.props.actions.getAlllist });
       }
    
       render() {
        return <SomeList loadData={this.state.data}/>;
    }
    

    因此,每次渲染 ScreenA 屏幕时,它都会获取数据。

    【讨论】:

    • ComponentDidMount() 仅在组件挂载时触发,而不是每次 View 进入前台时触发
    猜你喜欢
    • 1970-01-01
    • 2021-08-31
    • 2021-03-24
    • 2021-06-08
    • 2018-03-17
    • 1970-01-01
    • 1970-01-01
    • 2020-09-01
    • 2017-02-09
    相关资源
    最近更新 更多