Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

952
Views
La tienda del kit de herramientas Redux se restablece automáticamente al navegar entre páginas en el siguiente js

Soy un nuevo usuario de Next y he estado usando Redux con React durante mucho tiempo. Tuve muchos problemas para usar Redux con Next.

he terminado con esta solución

tienda.js

 import { configureStore } from '@reduxjs/toolkit'; import reducers from './rootReducer'; export function makeStore() { return configureStore({ reducer: reducers, }); } const store = makeStore(); export default store;

rootReducer.js

 import { combineReducers } from '@reduxjs/toolkit'; import tes from './test/tes'; const reducers = combineReducers({ test: tes, }); export default reducers;

_app.js

 import React from 'react'; import { Provider } from 'react-redux'; import store from '../redux/store'; import { createWrapper } from 'next-redux-wrapper'; const MyApp = ({ Component, ...rest }) => { return ( <Provider store={store}> <Component {...rest} /> </Provider> ); }; const makestore = () => store; const wrapper = createWrapper(makestore); export default wrapper.withRedux(MyApp);

Pero descubrí que cualquier uso de useDispatch Dentro de cualquier página, el motor de búsqueda no reconoce el contenido de la página después de obtener los datos.

 import React, { useEffect } from 'react'; import { Test } from '../../redux/test/tes'; import { useDispatch, useSelector } from 'react-redux'; import Link from 'next/link'; function TestPage() { const dispatch = useDispatch(); const { data } = useSelector((state) => state.test); useEffect(() => { dispatch(Test('hi')); }, []); return ( <div> <Link href="/"> <a>home</a> </Link>{' '} {data.map((name) => ( <h1>{name.title}</h1> ))} </div> ); } export default TestPage;

Se debe usar uno de los siguientes métodos de procesamiento previo

Me pregunto si esto es normal con el siguiente

o hay una mejor manera de hacerlo?


#1 Actualización

Ahora, después de mover la obtención de datos a getStaticProps

TestPage.js

 import React from 'react'; import { Test } from '../../redux/test/tes'; import { useSelector } from 'react-redux'; import Link from 'next/link'; import { wrapper } from '../../redux/store'; function TestPage({ pageProps }) { const { data } = useSelector((state) => state.test); console.log(data); return ( <div> <Link href="/"> <a>home</a> </Link>{' '} {data && data.map((name) => ( <h1>{name.name}</h1> ))} </div> ); } export const getStaticProps = wrapper.getStaticProps( (store) => async (context) => { const loading = store.getState().test.loading; if (loading === 'idle') { await store.dispatch(Test('hi')); } return { props: { }, }; } ); export default TestPage;

El problema ahora es que la tienda no actualiza useSelector return []

Aunque console.log (data) de getStaticProps los datos están presentes __NEXT_REDUX_WRAPPER_HYDRATE__ estoy atascado


#2 Actualización

Fue realmente difícil llegar aquí y después de eso, todavía hay problemas para obtener Redux con Next js

Ahora todo funciona hasta que navegar a cualquier página tenga getStaticProps o getServerProps

el estado se restablece automáticamente

tienda.js

 import reducers from './rootReducer'; import { configureStore } from '@reduxjs/toolkit'; import { createWrapper, HYDRATE } from 'next-redux-wrapper'; const reducer = (state, action) => { if (action.type === HYDRATE) { let nextState = { ...state, ...action.payload, }; return nextState; } else { return reducers(state, action); } }; const isDev = process.env.NODE_ENV === 'development'; const makeStore = (context) => { let middleware = []; const store = configureStore({ reducer, middleware: (getDefaultMiddleware) => getDefaultMiddleware().concat(middleware), devTools: isDev, preloadedState: undefined, }); return store; }; export const wrapper = createWrapper(makeStore, { debug: isDev });
over 4 years ago · Santiago Trujillo
2 answers
Answer question

0

1.) ¿El uso de Redux con Nextjs elimina la ventaja de SEO?

No, usar Redux con NextJs no obstaculiza la ventaja de SEO. Redux va bien con NextJS.

El problema radica en su implementación de la obtención de datos. NextJS no ve el contenido obtenido porque debe obtenerlo en getInitialProps , getServerSideProps o getStaticProps según la forma en que desea que funcione su aplicación.

Consulte la documentación de Obtención de datos de NextJS.

Tenga en cuenta que getServerSideProps y getStaticProps son las formas recomendadas de tratar con la obtención de datos.

Si opta por getStaticProps , necesitará getStaticPaths . Verifique esta respuesta para ver casos de uso y la diferencia entre getStaticPaths y getStaticProps , ya que puede ser confuso.

TLDR; En lugar de colocar la obtención de datos en un gancho useEffect, muévalo dentro de una getServerSideProps o getStaticProps .

over 4 years ago · Santiago Trujillo Report

0

Al final, esta forma solo funcionó Incluso la separación del estado del servidor y del Cliente no funcionó

con este parche jsondiff

rootReducer.js

 const rootReducer = createReducer( combinedReducers(undefined, { type: '' }), (builder) => { builder .addCase(HYDRATE, (state, action) => { const stateDiff = diff(state, action.payload); const isdiff = stateDiff?.test?.data?.[0]; const isdiff1 = stateDiff?.test1?.data?.[0] return { ...state, ...action.payload, test: isdiff ? action.payload.test : state.test, test1: isdiff1 ? action.payload.test1 : state.test1, }; }) .addDefaultCase(combinedReducers); } );

El único problema aquí es que tienes que probar cada cambio en cada pieza dentro del estado.

Dejaré la mejor respuesta hasta el final de la recompensa, gracias a todos.


actualización: porque un reductor de hidratos global puede ser excesivo. aquí hay un ejemplo para manejar la hidratación en cada rebanada

 import { createSlice, createAsyncThunk } from '@reduxjs/toolkit'; import { diff } from 'jsondiffpatch'; import { HYDRATE } from 'next-redux-wrapper'; const initialState = { data: [], }; export const TestFetch = createAsyncThunk( 'TestFetch', async (data, { rejectWithValue, dispatch }) => { try { const response = await fetch( 'https://jsonplaceholder.typicode.com/users' ); const d = await response.json(); return d; } catch (error) { return rejectWithValue(error.response.data.error); } } ); const test = createSlice({ name: 'test', initialState, reducers: { update: { reducer: (state, { payload }) => { return { ...state, data: payload }; }, }, }, extraReducers: { [HYDRATE]: (state, action) => { const stateDiff = diff(state, action.payload); const isdiff1 = stateDiff?.server?.[0]?.test?.data?.[0]; // return { // ...state, // data: isdiff1 ? action.payload.server.test.data : state.data, // }; state.data = isdiff1 ? action.payload.server.test.data : state.data; }, [TestFetch.fulfilled]: (state, action) => { state.data = action.payload; }, }, }); export const { update } = test.actions; export default test.reducer;
over 4 years ago · Santiago Trujillo Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!