首页 > 解决方案 > 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}, };
});

商店输出: redux-devtools-screnshot

这是商店返回空的客户端唯一页面:

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 (
        ...
    );
}

这是它的空商店: redux-devtools screenshot 空存储

我还如何从此页面访问商店数据?

编辑:我添加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);

标签: reactjsreduxreact-reduxnext.js

解决方案


推荐阅读