Как я могу иметь Next.js, например, выборку данных ( getInitialProps ) с React Router и React Loadable с использованием Razzle .У меня было выборка данных без реагирующей загрузки , но без разделения кода пакет приложений слишком велик, и загрузка страницы для клиентов занимает слишком много времени.
этот код работает, но я просто нене понимаю, что я делал около года назад (это немного отличается от предыдущего примера)
const promises = routes
.map((route) => {
const match = matchPath(req.url, route)
if (match && route.component) {
let promise
if (typeof route.component.preload === "function") {
promise = route.component.preload()
} else {
promise = Promise.resolve(route.component)
}
return promise
.then((res) => {
return res && res.__esModule ? res.default : res
})
.then((component) => {
let promises = []
// STATIC INTI ACTION
promises.push(store.dispatch(getToken()))
if (component.initialAction) {
let results = component.initialAction({ match })
results = Array.isArray(results)
? results
: [results]
results.forEach((result) => {
promises.push(store.dispatch(result))
})
}
return promises
})
}
return null
})
.filter((el) => el !== null)
// page not found
if (promises.length === 0) {
renderTree(req, res, store)
} else {
Promise.all(promises.map((data) => data.then((moreData) => moreData)))
.then((data) => {
Promise.all(data[0]).then(() => renderTree(req, res, store))
})
Server.js
const promises = []
routes.some((route) => {
const match = matchPath(req.url, route);
if (match) {
// route.component is React Loadable Component so getInitialData is undefined
if (route.component.getInitialData) {
promises.push(route.component.getInitialData({ match, req, res }))
}
return true;
}
return false;
});
Promise.all(promises)
.then(renderReact)
.catch(handleError)
// and at the end i will call
Loadable.preloadAll()
.then(sendResponseToUser)
маршруты:
[
{
path: "/",
exact: true,
component: Loadable({
loader: () => import("@views/Home"),
loading: Loading,
}),
},
{
path: "/shop",
exact: true,
component: Loadable({
loader: () => import("@views/Shop"),
loading: Loading,
}),
},
]
Мои компоненты выглядят так:
class Home extends React.Component {
// This works similarly to Next.js's `getInitialProps`
static getInitialData({ match, req, res }) {
return new Promise((resolve, reject) => {
setTimeout(() => {
resolve({
text: `
This text is server rendered if and only if it's the initial render.
Go to another route.
`,
currentRoute: match.pathname,
});
}, 500);
});
}
render() {
return <p>this is just a test</p>
}
}
У React Loadable Component есть метод preload (), который может загружать компонент, поэтому я попробовал: route.component.preload()
, но он не работает.
Я попытался загрузить-components, и у него тоже есть та же проблема, но я могу заменить реакционно-загружаемые на loadable-компоненты (моя предпочтительная библиотека - loadable-components, потому что это нормально с StrictMode).
на самом деле, после.js решил эту проблему (он использует Razzle), если бы я мог извлечь логику разделения кода и использовать ее в своем приложении или иметь какой-нибудь рабочий пример выборка данных и реагирующая загрузка вместе было бы бэто круто.