Warning: file_get_contents(/data/phpspider/zhask/data//catemap/8/perl/10.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Reactjs 将location.pathname添加到反应上下文_Reactjs - Fatal编程技术网

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
对象。只要记住使用
路由器
提供商,您就可以开始了