Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

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

javascript - what am I doing wrong with useContext?

I am trying to use the useContext from preact. It seems I am doing something wrong, because my Context give undefined values.

Here is the main file:

const {render, h, createContext} = window.preact
import htm from 'https://unpkg.com/htm?module'
const html = htm.bind(h)
import SampleComp from './sample-comp.js'

export const ContextOne = createContext()
export const ContextTwo = createContext()

const RootComp = (props) => {
  return html`
  <ContextOne.Provider value=${'ContextOne'}>
    <ContextTwo.Provider value=${'ContextTwo'}>
      <${SampleComp}/>
    </ContextTwo.Provider>
  </ContextOne.Provider>
  `
}

render(html`<${RootComp} />`, document.body);

and here is the sample component:

const {useContext} = window.preactHooks
const {h} = window.preact
import htm from 'https://unpkg.com/htm?module'
const html = htm.bind(h)
import {ContextOne, ContextTwo} from './index.js'


export default function SampleComp (props) {
  const one = useContext(ContextOne)
  const two = useContext(ContextTwo)
  return html`<div>${one} - ${two}</div>`
}

What am I doing wrong here? I have been trying to figure it out for a few hours now but no idea.

question from:https://stackoverflow.com/questions/65540875/what-am-i-doing-wrong-with-usecontext

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

1 Reply

0 votes
by (71.8m points)

I got it.

Just after posting the question I realized that by using htm I need to wrap the providers in the template string to be a variable. so correct would be:

const RootComp = (props) => {
  return html`
  <${ContextOne.Provider} value=${'ContextOne'}>
    <${ContextTwo.Provider} value=${'ContextTwo'}>
      <${SampleComp}/>
    </ContextTwo.Provider>
  </ContextOne.Provider>
  `
}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...