Next.js - 从其他路线导航时组件中没有数据
Next.js - no data in component when navigating from other route
我是 next.js 的新手。
我在后端呈现我的页面视图:
module.exports = (server, app) => {
server.get('/setup', (req, res) => {
const testData = {
name: "Test",
testProp: "testVal",
};
return app.render(req, res, '/setup', testData);
});
};
当我在浏览器中刷新 /setup
路线上的页面时,我可以看到 getInitialProps 中的数据,这很好。但是当我从另一条路线导航到 /setup
路线时,我看不到数据。为什么会发生这种情况,我该如何更改它才能看到数据?这是我的页面代码:
import { withAuth } from '../utils/withAuth';
const Setup = props => {
console.log(props); // when linking there is no expected data here
return(
<div>Setup here</div>
)
};
Setup.getInitialProps = async ctx => {
return { ...ctx.query };
};
export default withAuth(Setup);
从其他路线导航时,您不会在服务器端渲染,因此您必须在 getInitialProps 中从服务器获取数据。
import fetch from 'isomorphic-unfetch'
const Setup = (props) => {
console.log(props);
return(
<div>Setup here</div>
)
}
Setup.getInitialProps = async (ctx) => {
if (ctx.req) {
// server-side
return { ...ctx.query }
} else {
// client-side
const res = await fetch('API/setup')
const json = await res.json()
return { ...json }
}
}
我是 next.js 的新手。 我在后端呈现我的页面视图:
module.exports = (server, app) => {
server.get('/setup', (req, res) => {
const testData = {
name: "Test",
testProp: "testVal",
};
return app.render(req, res, '/setup', testData);
});
};
当我在浏览器中刷新 /setup
路线上的页面时,我可以看到 getInitialProps 中的数据,这很好。但是当我从另一条路线导航到 /setup
路线时,我看不到数据。为什么会发生这种情况,我该如何更改它才能看到数据?这是我的页面代码:
import { withAuth } from '../utils/withAuth';
const Setup = props => {
console.log(props); // when linking there is no expected data here
return(
<div>Setup here</div>
)
};
Setup.getInitialProps = async ctx => {
return { ...ctx.query };
};
export default withAuth(Setup);
从其他路线导航时,您不会在服务器端渲染,因此您必须在 getInitialProps 中从服务器获取数据。
import fetch from 'isomorphic-unfetch'
const Setup = (props) => {
console.log(props);
return(
<div>Setup here</div>
)
}
Setup.getInitialProps = async (ctx) => {
if (ctx.req) {
// server-side
return { ...ctx.query }
} else {
// client-side
const res = await fetch('API/setup')
const json = await res.json()
return { ...json }
}
}