【问题标题】:React Redux, load data from the API on first page load ONLY. Render component once data is loadedReact Redux,仅在第一页加载时从 API 加载数据。加载数据后渲染组件
【发布时间】:2020-09-19 09:08:21
【问题描述】:

我肯定在我的应用程序的核心做错了什么。

我认为它在哪里我正在向我的 API 发出请求。我也不满意 firstLoad 标记告诉应用调用 API。

我正在使用 React/Redux - 从这个样板 https://www.npmjs.com/package/create-react-app-redux 构建。

它使用 mapStateToProps、mapDispatchToProps 和 connect 将所有内容粘合在一起。

所以我有一个名为“Shop”的组件

// only true when user first visits url OR presses F5 to refresh. 
// Its conveniently false when page rerenders
var firstLoad = true; 
const Shop = ({ stateProps, dispatchProps }) => {
  if(firstLoad) {
    firstLoad = false;
    // dispatchProps contains a method called changeState that will update state.shops to the result from the API. It will also set state.loading to true while calling and false when finished.
    // Note, I am not modifying state directly. The dispatchProps wraps the action that does so
    server.GetShops({url: "api/shops", updateField:"shops", loading:true, token:"abc-xyz"}, dispatchProps);
  }

  if(stateProps.loading) {
    return (
      <div>loading...</div>
    );
  }

  var shopUrl = window.location.href; // extract the part of the url after the domain

  var selectedShop = stateProps.shops.find(s => {
      return s.url === shopUrl;
  });

  if(!selectedShop) {
    window.location.href = "/";
  }

  return (
    <div>
      {selectedShop.welcomeMessage}
    </div>
  );
}

我遇到的问题是我必须刷新两次才能查看何时更改了welcomeMessage。

因此,如果它最初来自数据库的“hello world”,我将其更改为数据库中的“hello UK”。

当我刷新页面时,我希望应用程序能够获取数据并显示加载。 当它完成获取数据时,会发生重新渲染,并且应该在欢迎消息中显示 Hello UK。

但是,直到第二次页面刷新才会发生这种情况。

我所描述的对任何人都有意义吗?

【问题讨论】:

  • 为什么不使用 useEffect 或 componentDidMount 等生命周期方法
  • 老实说,对于 create-react-app-redux 模板文件夹结构,我还没有弄明白,感觉就像只使用 react 作为 lib 不同的野兽。我不知道这将如何与为商店和 thunk 的配置提供的管道一起工作。

标签: reactjs react-redux create-react-app


【解决方案1】:

您没有根据selectedShop 的值进行任何更改 您应该将 selectedShop 的值保存在本地状态变量中

const [ selectedShop , setSelectedShop ] = useState({});

然后每当从 api 调用更改值时更新本地状态值

useEffect( () => {

  var selectedShop = stateProps.shops.find(s => {
      return s.url === shopUrl;
  });

   setSelectedShop(selectedShop);

} , [stateProps.shops]) 

现在当 stateProps 中的值发生变化时,它将更新本地状态值并触发重新渲染。

【讨论】:

  • 仍在努力。我认为你在做某事:))
  • 谢谢。 useEffect 真的帮助了我。我以前从未使用过。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2011-08-15
  • 2020-09-18
  • 1970-01-01
  • 2012-11-01
相关资源
最近更新 更多