【问题标题】:Can I wait for my component to be connected for react-redux?我可以等待我的组件连接到 react-redux 吗?
【发布时间】:2020-08-22 05:33:15
【问题描述】:

如何等待 react-redux 返回我的新连接组件?基本上,我有一个索引屏幕,我在其中对数据库进行查询以保存客户端,该 api 调用的响应是我想要触发我的 SAVE_CUSTOMERS 操作然后在视图中制作地图的参数。

这个错误是因为我想要制作地图的对象尚不存在,这就是为什么我伪造一个等待该哈希以及它是否有效。

我有几种方法可以强制它工作,但我来这里是为了一个奇特的解决方案????

customers.js

import React from "react";
import bridge from "../../helpers/bridge/index";
import { save_customers } from "../../../actions/customers";
import CustomersUI from "../../components/Customers/CustomersUI";
import { connect } from "react-redux";

class CustomersScreen extends React.Component {
  constructor(props) {
    super(props);
  }

  componentDidMount() {
    bridge
      .getCustomers(this.props.user.access_token)
      .then((customers) => this.props.save_customers(customers))
      .catch((error) => console.error(error));
  }

  render() {
    return (
      <CustomersUI
        customers={this.props.customers}
      />
    );
  }
}

export default connect(
  (state) => ({
    user: state.user,
    customers: state.customers,
  }),
  {
    save_customers: save_customers,
  }
)(CustomersScreen);

我的减速器

export default (state = {}, action) => {
  switch (action.type) {
    case "SAVE_CUSTOMERS":
      return action.customers;
    default:
      return state;
  }
};

还有……动作,

export function save_customers(customers) {
  return {
    type: "SAVE_CUSTOMERS",
    customers,
  };
}

输出

显然我有一个 combineReducers 导出所有内容。

也许等待组件被连接并不是解决它的最花哨的方法,它只是我对它的最接近的想法。不到 1 周前,我还在使用 React Native,之前从未使用过 Redux。谢谢!

【问题讨论】:

  • ...props.customers.map... 来自哪里?
  • 来自我的用户界面。我在哪里做.map。我不想添加它以免听起来多余。类似于props.customer.map((customer)=&gt; (COMPONENT...))

标签: reactjs react-native redux react-redux expo


【解决方案1】:

您所在州的customers 数组在等待来自getCustomers 的响应时可能未定义。因此,在您的渲染方法上,您应该仅在定义了customers 时有条件地渲染子CustomersUI

 render() {
    const { customers } = this.props;
    return (
      customers && (
        <CustomersUI
          customers={this.props.customers}
        />
      )
    );
  }

或者,CustomersUI 组件应该处理未定义的值,这样它就不会抛出该错误。

【讨论】:

  • 这看起来不是很花哨。主要是因为我可以从我的提供商那里获得多个阵列,并且在这种情况下用户体验会受到很大影响。理想的情况是渲染,然后根据需要进行更新。除此之外,它也不起作用?
  • 嗯..它不起作用?意味着组件根本不渲染..?还是..?
猜你喜欢
  • 2016-03-09
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2018-08-07
  • 2017-12-17
  • 1970-01-01
  • 2017-06-23
  • 1970-01-01
相关资源
最近更新 更多