store.getState()在index.js中返回空值



使用nextjs进行服务器端渲染,试图从getServerSideProps()中的redux存储中获取状态。但是得到空值。

const productList = useSelector(state => state.productList) const { loading, error, products } = productList组件内的客户端从redux获取数据工作正常。但是当使用getServersideProps()时,我得到空结果。

index.js:

import store from '../redux/store'
export default function Home({products, error, loading}) {
const dispatch = useDispatch()
useEffect(() => {
dispatch(listProducts())
}, [dispatch])
return (
<>
<Header />
<Products loading={loading} error={error} products={products} />
<Footer />
</>
)
}
export async function getServerSideProps() {
const state = store.getState()
const { loading, error, products } = state.productList
return {props: {products: products, loading: loading, error: error}}
}

*注意:即使我在组件内执行console.log(store.getState()),它仍然返回空数组

减速器:

export const productListReducer = (state = { products: [] }, action) => {
switch (action.type) {
case 'PRODUCT_LIST_REQUEST':
return { loading: true, products: [] }
case 'PRODUCT_LIST_SUCCESS':
return { loading: false, products: action.payload }
case 'PRODUCT_LIST_FAIL':
return { loading: false, error: action.payload }
default:
return state
}
}

行动:

import axios from 'axios'
export const listProducts = () => async (dispatch) => {
try {
dispatch({ type: 'PRODUCT_LIST_REQUEST' })
const { data } = await axios.get('/api/products')
dispatch({
type: 'PRODUCT_LIST_SUCCESS',
payload: data
})
} catch (error) {
dispatch({
type: 'PRODUCT_LIST_FAIL',
payload: error.response && error.response.data.message
? error.response.data.message : error.message
})
}
}

store.js:

const reducer = combineReducers({
productList: productListReducer,
categoryList: categoryListReducer,
})
const initialState = {}
const middleware = [thunk]
const store = createStore(
reducer, initialState, composeWithDevTools(applyMiddleware(...middleware))
)
export default store

尝试直接调用getState(),不要忘记将其作为参数传递,并确保将store传递给应用组件

export async function getServerSideProps(getState) {
const state = getState()
const { loading, error, products } = state.productList
return {props: {products: products, loading: loading, error: error}}
}

问题是useDispatch是一个React- redux函数,但是商店还没有连接到React组件。

代替useDispatch试试store.dispatch:

import store from '../redux/store'
export default function Home({products, error, loading}) {
useEffect(() => {
store.dispatch(listProducts())
})
return (
<>
...
</>
)
}

注意,当该效果运行时,数组传递给useEffect控制,因此传递分派函数没有意义。

你也可以使用React-Redux将Redux存储连接到React组件,并继续使用useDispatch

相关内容

  • 没有找到相关文章

最新更新