【发布时间】: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