【问题标题】:Correct way to get state value from inside getServerSideProps getState() or useSelector()?从 getServerSideProps getState() 或 useSelector() 中获取状态值的正确方法?
【发布时间】:2021-04-23 23:49:44
【问题描述】:

所以我一直在尝试使用 next-redux-wrapper 并向我的 api 端点发出请求以获取带有 redux-saga 的博客。我能够将数据提取到该州。我唯一的疑问是,从国家获得特定价值的正确方法是什么?我知道这两种解决方案是在getServerSideProps() 内使用store.getState() 还是在函数组件中使用useSelector() 挂钩?

据我了解,我认为使用useSelector() 会违反服务器端渲染,因为它会调用客户端中的数据。对吗?

我的代码使用useSelector()

export default function BlogsList(){
    const blogs = useSelector(state => state.blogReducer.blogReducer.blog);

    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>
                        <p>{item.body_html}</p>
                        <p>{item.created_on}</p>
                    </li>
                ))}
            </ul>
        </div>
    );
}

export const getServerSideProps = wrapper.getServerSideProps( async ({store, req}) =>{
    store.dispatch({type: FETCH_BLOG_LIST});
    store.dispatch(END);
    await store.sagaTask.toPromise();
});

我的代码使用store.getState()

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>
                        <p>{item.body_html}</p>
                        <p>{item.created_on}</p>
                    </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 blog = store.getState();
    const blogs = blog.blogReducer.blog;
      
    return { props: {blogs}, };
});

哪种方法正确遵循服务器端渲染逻辑?

【问题讨论】:

    标签: reactjs redux next.js redux-saga


    【解决方案1】:

    您使用store.getState (): 的代码是正确的方法,正如您所提到的,useSelector 用于在客户端获取状态。使用 next-redux-wrapper 创建了两个存储,一个用于服务器(getStaticProps,getServerSideProps),一个用于客户端

    【讨论】:

    • 所以在水化之后,如果我需要从商店访问一些数据,那么在客户端使用useSelector() 是否合适?
    • 是的,您仍然需要发送相同的操作
    • 如果这回答了您的问题,您可以将其标记为已接受的回答
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2022-06-24
    • 2020-02-23
    • 2021-10-16
    • 1970-01-01
    • 2021-08-23
    • 1970-01-01
    • 2020-01-22
    相关资源
    最近更新 更多