Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
347 views
in Technique[技术] by (71.8m points)

reactjs - Add location.pathname to React context

I'm doing some theming for a gatsby project I'm working on. I have the ThemeContext.Provider and ThemeContext.Consumer. The layouts differ depending on what page you're on. I was wondering if it's possible to store location.pathname in the ThemeProvider and have the path returned in my theme object as the page route changes. I want to pass the path to specific components to adjust the layout depending on the route. Thank you.

ThemeProvider:

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>
  )
}
question from:https://stackoverflow.com/questions/65623349/add-location-pathname-to-react-context

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

In that case, you're storing unnecessary data in a context which make the possibility of bad rendering performance higher.

All you need is to use useLocation hook if you use Function Component or withRouter HOC if you Class Component to access the location object in your Component. just remember to use Router provider and you good to go.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...