React Redux,仅在第一页加载时从 API 加载数据。加载数据后渲染组件

React Redux, load data from the API on first page load ONLY. Render component once data is loaded

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

我认为是 我正在向我的 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。

然而,直到第二次页面刷新时才会发生这种情况。

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

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

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

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

useEffect( () => {

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

   setSelectedShop(selectedShop);

} , [stateProps.shops]) 

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