【问题标题】:React/Redux - when switching between routes content rendering is with delayReact/Redux - 在路由之间切换时,内容渲染有延迟
【发布时间】:2018-11-29 14:55:15
【问题描述】:

我是 reactjs/redux 的初学者,我有一个无法修复的错误。

从数据库渲染不同数据的 2 个路由之间存在错误。

/dashboard 路由正在渲染正在获取 user.products 的组件

/products 路由正在渲染正在获取 all.products 的组件

所以基本上在仪表板路线上,您应该只看到您上传的那些产品,而在产品路线上,您可以看到所有用户上传的所有产品。

问题在于,每当您在这两个路由之间切换时,内容的呈现都会延迟。当您从/products 路由到/dashboard 时,您将在仪表板上看到所有产品,然后它会重新正确呈现

Example

Dashboard 组件呈现 ProductsList:

class ProductsList extends Component {
  componentDidMount() {
    this.props.fetchProduct();
  }
render() {
    return <div>{this.renderProducts()}</div>;
  }
}

function mapStateToProps({ products }) {
  return { products };
}

export default connect(
  mapStateToProps,
  { fetchProduct },
)(ProductsList);

Products 组件呈现 AllProductsList:

class AllProductsList extends Component {
  componentDidMount() {
    this.props.fetchAllProduct();
  }
  render() {
    return (
      <div>{this.renderProducts()}</div>
    );
  }
}

function mapStateToProps({ allproducts }) {
  return { allproducts };
}

export default connect(
  mapStateToProps,
  { fetchAllProducts },
)(AllProductsList);

在加载/dashboard 页面时,props.products 显示为空数组,在提取完成后它会填充此数组。

当我从/dashboard 路由到/products 页面时,props.allproducts 首先填充了为products 获取的数据,在fetchAllProducts() 完成后它会发生变化

Console log

【问题讨论】:

  • 您的 fetch 函数是否执行 http 调用?
  • 所以使用了相同的 api,响应 json 有任何属性来保存这些是否是用户选择或上传的产品?
  • 我认为问题是你在 fetch 解决之前切换路由,你可以在 fetch 更新状态后切换。
  • @DILEEPTHOMAS 有两个独立的 API module.exports = app =&gt; { app.get("/api/product", async (req, res) =&gt; { const products = await Product.find({ _user: req.user.id }); res.send(products); }); app.get("/api/allproducts", async (req, res) =&gt; { const allProducts = await Product.find({}); res.send(allProducts); });
  • 所以 products 是 reducer ,你是在同一个变量还是不同的变量中保存两个 api 响应?

标签: javascript reactjs react-redux react-router


【解决方案1】:

因此,对于两个 api,您持有相同的变量。这就是为什么在加载 AllProducts 组件时,您会在几分之一秒内看到用户的 productsList 数据,反之亦然。

秒的分数是 API 解决或拒绝的时间。或者应该说是 API 的挂起状态。

我希望这可以引出您的问题并解决问题。

如果需要对帖子添加任何内容,请告诉我。

【讨论】:

    【解决方案2】:

    componentDidMount() {}改为componentWillMount(){}

    问题是您在 fetchRequest 和 API 响应之间存在延迟,还要记住您需要时间来更新商店和渲染产品。

    在商店没有改变之前,你不会得到产品。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2019-01-10
      • 2020-09-12
      • 1970-01-01
      • 2019-12-07
      • 2017-04-23
      • 1970-01-01
      • 2015-08-28
      相关资源
      最近更新 更多