[英]React/Nextjs - know what page is rendered on _app.js
So I'm trying to render my web nav and footer on my _app.js.所以我试图在我的 _app.js 上渲染我的 web 导航和页脚。 I wanted to dynamically change the style of my nav/footer depending on the page being accessed.
我想根据访问的页面动态更改导航/页脚的样式。 I thought about putting the nav and footer to the individual pages instead but i don't think it's best practice.
我考虑过将导航和页脚放在各个页面上,但我认为这不是最佳做法。
How do I know what page im accesing inside _app.js我如何知道我在 _app.js 中访问的页面
ex.前任。
pages/index.js
pages/profile.js
in my _app.js i will change the style of nav and footer depending on the page accesed.在我的 _app.js 中,我将根据访问的页面更改导航和页脚的样式。
I think you can based on Router.pathName in Nextjs to change the style of nav and footer like this:我认为您可以基于 Nextjs 中的 Router.pathName 来更改导航和页脚的样式,如下所示:
const get firstPathName = pathName => pathName.split("/")[1]
export default class extends React.Component {
getInitialProps ({ pathname, query }) {
switch(firstPathName(pathname)) {
case "":
case "index": // style nav and footer with index.js
break;
case "profile": // style nav and footer with profile.js
break;
default: // do with default
break;
}
}
}
See this PR to more information: Add pathname and query to the argument of getInitialProps有关更多信息,请参阅此 PR:将路径名和查询添加到 getInitialProps 的参数
EDIT编辑
In your case, My suggest is connect to Redux
and save current url at level Component
into store.在您的情况下,我的建议是连接到
Redux
并将当前level Component
保存到存储中。 Then, in _app.js
, you will get this to handle style nav or footer.然后,在
_app.js
中,您将使用它来处理样式导航或页脚。 Example:例子:
At Component:在组件:
const connectToRedux = connect(null, dispatch => ({
changeCurrentUrl: () => dispatch({
type: "CHANGE_CURRENT_URL", payload: firstPathName(Router.pathName)
})
}))
componentWillMount() {
if (process.browser) { // make sure isClient in Nextjs
this.props.changeCurrentUrl()
}
}
At Reducer:在减速机:
export default {
currentUrl: (state = "", action) => {
if (action.type === "CHANGE_CURRENT_URL") {
state = action.payload;
}
return state;
}
}
At app.js // make sure connected to Redux at here在 app.js // 确保在此处连接到 Redux
componentWillMount() {
const { currentUrl } = this.props
// handle style nav and footer here depending on url
}
You may use the document
object.您可以使用
document
object。
const [url, setUrl] = useState('')
useEffect(() => {
setUrl(document.URL)
}, [document.URL])
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.