【发布时间】:2023-03-07 20:26:01
【问题描述】:
我正在尝试实现一个简单的测试用例,以便将 Redux-thunks 与 Next JS 一起使用,但不断收到错误
错误:页面“/”的“getInitialProps”结果中的循环结构。 https://err.sh/zeit/next.js/circular-structure
我之前已经让这一切工作了一次,我确信我犯了一些明显的错误。 我很感激你能提供的任何帮助。我已经戳了一个小时,但我没有看到我哪里出错了......
我已将其追溯到我的 thunk 中的调度,即 action-creators.js 中以下代码中的 dispatch(getItemsSuccess(data))。也就是说,如果我删除该调度,我不会收到错误消息。
// action-creators.js
import {GET_ITEMS_SUCCESS} from "./action-types"
import axios from 'axios'
export const getItemsSuccess = (data) => ({ type: GET_ITEMS_SUCCESS, data });
export const getItems = () => async (dispatch,getState) => {
try {
const data = await axios.get(`https://api.themoviedb.org/3/genre/movie/list?api_key=12345xyz`)
return dispatch(getItemsSuccess(data))
} catch(e) {
console.log(`error in dispatch in action-creators: ${e}`)
}
}
我的 _app.js 是
import React from 'react'
import {Provider} from 'react-redux'
import App, {Container} from 'next/app'
import withRedux from 'next-redux-wrapper'
import configureStore from '../redux/configure-store'
class MyApp extends App {
static async getInitialProps({Component, ctx}) {
let pageProps = {}
if (Component.getInitialProps) {
pageProps = await Component.getInitialProps(ctx)
}
return {pageProps}
}
render() {
const {Component, pageProps, store} = this.props
return (
<Container>
<Provider store={store}>
<Component {...pageProps} />
</Provider>
</Container>
)
}
}
export default withRedux(configureStore, { debug: true })(MyApp);
我的 index.js 是
import React, {Component} from 'react'
import {connect} from 'react-redux'
import {getItems} from "../redux/action-creators"
class Index extends Component {
static async getInitialProps({store}) {
try {
await store.dispatch(getItems())
} catch(e) {
console.log(`error in dispatch in index.js: ${e.message}`)
}
}
render() {
return <div>Sample App</div>
}
}
export default connect(state => state)(Index)
最后我这样配置商店
import { createStore, applyMiddleware } from 'redux';
import thunk from 'redux-thunk';
import rootReducer from './root-reducer';
const bindMiddleware = middleware => {
if (process.env.NODE_ENV !== 'production') {
const { composeWithDevTools } = require('redux-devtools-extension');
return composeWithDevTools(applyMiddleware(...middleware));
}
return applyMiddleware(...middleware);
};
function configureStore(initialState = {}) {
const store = createStore(
rootReducer,
initialState,
bindMiddleware([thunk]),
);
return store;
}
export default configureStore;
再次,非常感谢任何帮助 - 我已经研究了一段时间,但没有看到丢失的部分......
【问题讨论】:
标签: reactjs redux react-redux redux-thunk next.js