首页 > 解决方案 > React Native 从 API 获取父与子的数据

问题描述

我是 React Native 的新手,所以想知道关于以下场景的最佳实践。

我的通知屏幕组件包含嵌套的子组件,如下所示:

NotificationsScreen ReadSection ReadList UnreadSection UnreadList

我应该在哪里处理状态并进行 API 调用?

选项1:

在 ScreenComponent 构造函数和 componentDidMount 中:

this.state = {

  loading: true,
  notifications: [],
  error: ''

componentDidMount() {
    const headers = {
      Authorization: this.props.jwt
    };
    axios({
      method: 'GET',
      url: 'http://localhost:3000/notifications',
      headers: headers,
    }).then((response) => {
      this.setState({
        notifications: response.data.data,
        loading: false

然后我必须将通知状态对象作为道具传递给子组件 ReadList 和 UnreadList,分别过滤掉已读和未读通知并呈现列表。

选项 2:

对子 List 组件中的 API 进行 API 调用:

constructor(props) {
    super(props);
    this.state = {
      loading: true,
      read_notifications: [],
      error: ''
    };
  }

  componentDidMount() {
    const headers = {
      Authorization: this.props.jwt
    };
    axios({
      method: 'GET',
      url: 'http://localhost:3000/notifications?status=read',
      headers: headers,
    }).then((response) => {
      this.setState({
        notifications: response.data.data,
        loading: false

在这种情况下,我将有 2 个 API 调用,每个组件调用一个,这并不理想,而且我不知道如何在数据加载时处理父控制器的加载渲染,因为子仅渲染列表,而不是整个屏幕。

所以我猜选项 1 会更可取,但这意味着将整个通知数组传递给子组件,并对每个子组件中潜在的数百条记录进行过滤。

有没有我没有想到的第三种选择?提前致谢。顺便说一句,我还没有使用 Redux,所以现在想避免任何涉及外部通量库的解决方案。

标签: reactjsreact-native

解决方案


有两种类型的组件作为最佳实践。有状态和纯组件。有些人也称它们为容器和展示组件。状态始终应由有状态/容器组件处理。展示组件不处理状态,只访问父组件状态。


推荐阅读