reactjs - NextJS:从客户端或服务器端的另一个页面调用存储时,Redux 存储返回空
问题描述
我正在服务器端的页面中调用数据列表,该页面将用于 redux 存储。我希望这些数据可用于其他页面。
现在,我有另一个页面,我想在客户端编辑一篇文章。我正在从先前填充的 redux 商店中获取一篇随机文章(仅用于测试)useSelector()
。但是该页面的商店返回为空!为什么这个页面中没有填充的商店?
为了测试,我尝试wrapper.getServerSideProps()
通过访问服务器上的商店来在服务器端呈现页面,但它也返回空!
redux store 填充博客列表的页面:
export default function BlogsList({blogs}){
return(
<div className="mainCon">
<ul>
{blogs.map((item) => (
<li key={item.author}>
<span>{item.author}</span><br/>
<span>{item.title}</span>
<h4>{item.body_delta}</h4>
</li>
))}
</ul>
</div>
);
}
export const getServerSideProps = wrapper.getServerSideProps( async ({store, req}) =>{
store.dispatch({type: FETCH_BLOG_LIST });
store.dispatch(END);
await store.sagaTask.toPromise();
const myStore = store.getState();
const blogs = myStore.blogReducer.blog;
return { props: {blogs}, };
});
这是商店返回空的客户端唯一页面:
export default function editBlog(){
const myBlog = useSelector(state => state.blogReducer.blog);
const body_delta = myBlog[1].body_delta;
console.log(body_delta); // Throws TypeError: Cannot read property 'body_delta' of undefined
// Since the store is empty here
return (
...
);
}
我还如何从此页面访问商店数据?
编辑:我添加getInitialProps
了_app.js
但商店仍然是空的!
class MyApp extends App {
static getInitialProps = async ({Component, ctx}) => {
return {
pageProps: {
...(Component.getInitialProps ? await Component.getInitialProps(ctx) : {}),
},
};
};
render() {
const {Component, pageProps} = this.props;
return (
<Component {...pageProps} />
);
}
}
export default wrapper.withRedux(MyApp);
解决方案
推荐阅读
- ruby - 按百分比选择数组中的项目
- autoconf - 为 OpenMPI 1.3 定义宏
- php - PHP MySQL双重提交使用两个SESSION
- java - Spring 安全性没有考虑分配给某些资源的角色 - Spring BOOT
- spring - Amazon Web Services - 部署 Spring Boot 应用程序
- r - R中两个类的预测类概率
- python-3.x - 多标签分类器代码错误
- angularjs - 路线:控制器没有被调用
- android - Xamarin.Android.Support.Design 导致启动时崩溃
- javascript - 如何从这个脚本中取出动画?