【问题标题】:How can I reRender Child Component from Main Component when state changes in RN 0.61?当 RN 0.61 中的状态发生变化时,如何从主组件重新渲染子组件?
【发布时间】:2019-12-31 11:09:08
【问题描述】:

我有两个组件 Main 和 Child

export default class Main extends Component {

  render() {
    return (
      <View>
        <Child item={this.state.selectedItem} />
      </View>
    )
  }

}


export default class Child extends Component {

  state = {
    newItem: null
  };

  organiseProductOptions() {
    const { item } = this.props;
    Async Request with item.ID... {
      setState({ newItem: response })
    }
  }

  componentDidMount() {
    this.organiseProductOptions();
  }

  render() {
    return (
      <View>
        <Text>{this.state.newItem.name}</Text>
      </View>
    )
  }

}

通常,this.organiseProductOptions() 函数在 componentDidMount() 初始状态下工作。但是,当我尝试重新渲染 Child 时,render() 方法正在工作,但 componentDidMount() 不工作。

当我在主组件中设置状态 selectedItem 属性时,如何触发子组件中的 this.organiseProductOptions() 函数?

请注意,子组件有自己的状态。

【问题讨论】:

    标签: react-native


    【解决方案1】:

    由于Child 仅安装一次,您可以检查Child 的道具何时更改并执行您的请求。添加

    componentDidUpdate(prevProps) {
      if (prevProps.item !== this.props.item) { // 'item' is changed
        this.organiseProductOptions();
      }
    }
    

    【讨论】:

    • 非常感谢...你拯救了我的一天...新年快乐
    【解决方案2】:

    子组件重新渲染当 props 改变但它没有重新安装。所以当孩子挂载时,它会将newItem设置为this.props.item,但之后newItem将永远不会改变。

    标准做法是在您的子组件中的任何地方都使用 this.props.item。

    【讨论】:

    • 嗨,James,感谢您的回答,但正如之前所说的,子组件有自己的状态。所以我必须进行异步 api 调用,然后我必须编写响应。
    • 您的子组件似乎不太可能需要为基本相同的事情拥有自己的状态......您最终将没有单一的事实来源。最好在父级中处理您的 API 调用并将其传递下去。
    猜你喜欢
    • 2021-07-09
    • 1970-01-01
    • 2020-03-19
    • 1970-01-01
    • 2020-02-27
    • 2021-06-12
    • 1970-01-01
    • 1970-01-01
    • 2020-09-30
    相关资源
    最近更新 更多