【问题标题】:getContext and withContext not workinggetContext 和 withContext 不起作用
【发布时间】:2017-07-24 23:01:15
【问题描述】:

我一直在尝试将 id 传递给具有上下文的其他组件,但我得到了未定义,在某个地方我出错了。 据我了解,我们应该将上下文作为道具。 有什么想法吗?

import {compose,withContext} from 'recompose'


const ComponentOne = ({id}) => {
  console.log(id) // cizlory7iji600149711su9vj
...
}

const Context = withContext(
{id:React.PropTypes.string},
(props) => ({id:props.id})
)


export default compose(Context)(ComponentOne)

SecondComponent.js

import {compose,getContext} from 'recompose'

    const ComponentTwo = ({id}) => {
      console.log(id) // undefined
     ...
    }

    const GetContext = getContext(
      {id:React.PropTypes.string}
    )


    export default compose(GetContext)(ComponentTwo)

【问题讨论】:

  • ComponentTwo 绝对是 ComponentOne 的孩子,对吧?也许发布一个 jsfiddle。
  • 谢谢,就是这样,不知道我怎么错过了那个关键的部分......
  • Np,添加了一个答案。

标签: reactjs recompose


【解决方案1】:

上下文只能通过传递道具从父母传递给孩子,而不是兄弟姐妹。

使ComponentTwo 成为ComponentOne 的子级。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-01-01
    • 2020-10-08
    • 2020-10-22
    相关资源
    最近更新 更多