Reactjs 将location.pathname添加到反应上下文
我正在为盖茨比的一个项目做主题。我有Reactjs 将location.pathname添加到反应上下文,reactjs,Reactjs,我正在为盖茨比的一个项目做主题。我有主题的econtext.Provider和主题的econtext.Consumer。布局根据您所处的页面而有所不同。我想知道是否可以将location.pathname存储在主题Provider中,并在页面路径更改时将路径返回到我的主题对象中。我想将路径传递给特定组件,以根据管线调整布局。多谢各位 主题提供者: import React, { useState, createContext } from 'react' const defaultState
主题的econtext.Provider
和主题的econtext.Consumer
。布局根据您所处的页面而有所不同。我想知道是否可以将location.pathname
存储在主题Provider
中,并在页面路径更改时将路径
返回到我的主题
对象中。我想将路径传递给特定组件,以根据管线调整布局。多谢各位
主题提供者:
import React, { useState, createContext } from 'react'
const defaultState = {
dark: false,
setDark: () => {},
}
export const ThemeContext = createContext(defaultState)
interface ThemeProviderProps {
children: any
}
export const ThemeProvider = (props: ThemeProviderProps) => {
const { children } = props.children
const [dark, setDarkTheme] = useState<boolean>(false)
const setDark = () => {
setDarkTheme(true)
}
return (
<ThemeContext.Provider
value={{
dark,
setDark,
}}
>
{children}
</ThemeContext.Provider>
)
}
import React,{useState,createContext}来自“React”
const defaultState={
黑暗:错,
setDark:()=>{},
}
导出常量ThemeContext=createContext(默认状态)
接口,用于支持ProviderProps{
孩子们:有吗
}
导出常量ThemeProvider=(道具:ThemeProviderProps)=>{
const{children}=props.children
常数[dark,setDarkTheme]=使用状态(false)
常量setDark=()=>{
设置暗色调(真)
}
返回(
{儿童}
)
}
在这种情况下,您将不必要的数据存储在一个上下文中,这会增加渲染性能差的可能性
如果使用Function Component
则只需使用useLocation
hook,如果使用Class Component
则只需使用withRouter
HOC即可访问组件中的location
对象。只要记住使用路由器
提供商,您就可以开始了