【发布时间】:2020-11-30 04:27:54
【问题描述】:
需要一个 react pro 来帮助我。提前致谢!
我正在尝试找到一个使用 redux 和 NEXT JS 的最佳位置,而不会使设置过于复杂。
GOAL :是利用 getInitialProps(for SSR) 来调度动作(尤其是涉及 API 请求的动作),以便预先加载数据并进行 SSR 处理。
为了实现这一点,我已经完成了这个设置:
_app 组件:
// to connect redux with react
import { Provider } from 'react-redux';
import { createWrapper } from 'next-redux-wrapper';
import { createStore, applyMiddleware, compose } from 'redux';
import thunk from 'redux-thunk';
// REDUCER
import reducers from '../redux/reducers';
// STORE
const store = createStore(reducers, applyMiddleware(thunk));
const AppComponent = ({ Component, pageProps }) => {
return (
<Provider store={store}>
<Component {...pageProps} />
</Provider>
)
}
AppComponent.getInitialProps = async (appContext) => {
let pageProps = {};
if (appContext.Component.getInitialProps) {
pageProps = await appContext.Component.getInitialProps(appContext.ctx);
};
return { ...pageProps }
}
// returns a new instance of store everytime its called
const makeStore = () => store;
const wrapper = createWrapper(makeStore);
export default wrapper.withRedux(AppComponent);
着陆页(pages/index.js):
import { connect } from 'react-redux';
import { fetchPosts } from '../redux/actions';
import { bindActionCreators } from 'redux';
import { useEffect } from 'react';
import Link from 'next/link';
const LandingPage = ({ posts }) => {
console.log('POSTS', posts); // <-- NOT getting posts for some reason via GIPs() !!!
return <h1>Home page</h1>
}
LandingPage.getInitialProps = async (ctx, { store }) => {
await store.dispatch(fetchPosts());
const posts = await store.getState().posts;
console.log('RETURNING POSTS', posts) // <-- this returns the list of posts
return { ...posts }
}
export default LandingPage;
操作:
// custom axios function
import api from '../../api';
export const fetchPosts = () => async (dispatch) => {
const response = await api.get('/posts');
dispatch({
type: 'FETCH_POSTS',
payload: response.data
});
};
ISSUE:虽然 getInitialProps() 是控制台登录 POSTS 列表的事件,但我无法将 POSTS 从 getInitialProps 检索到 LandingPage 组件。 当我控制台记录帖子甚至道具时,它显示未定义。
有没有更好的方法来做到这一点?我在这里错过了什么?
【问题讨论】:
标签: reactjs redux react-redux next.js server-side-rendering