代码之家  ›  专栏  ›  技术社区  ›  Chen

上下文API使用者值未定义

  •  0
  • Chen  · 技术社区  · 7 年前

    我有一个孙子的组件,消费者从他们的祖父母。但是,上下文值未定义:

    文件1:

    export const WTContext = createContext();
    
    export default class A extends Component {
    
        ...
        render(){
            ...
            const contextValue={state: { items: [] }, actions: { doA: () => {}}}
            return (
                <WTContext.Provider value={contextValue} >
                    ...
                </WTContext.Provider>
            }
        }
    }
    

    文件2:

    export default function B(){
      return (
         <WTContext.Consumer>
            {({state}) => (
              ...
              return (
                 <div>
                    {state.items.map(...<C/>)} //all good, B use context.
                 </div>
                 {state.items
              )
            )}
         </WTContext.Consumer>
      )
    }
    

    文件3:

    export default function C(props){
       return (
           <WTContext.Consumer>
               {({ state, actions }) => {
                    // <-- Cannot read property 'state' of undefined
                    ...
    
               }
           </WTContext.Consumer>
       )
    }
    

    所以映射 B ,显示多个 C 组件,具有上下文消费者价值 undefined . 导入是有效的,但是我不明白为什么提供程序传递的值是 未定义 在第二层嵌套(因为第一层看起来不错, 乙 它确实按要求使用上下文)。

    2 回复  |  直到 7 年前
        1
  •  0
  •   Asif vora    7 年前

    使用创建上下文 React.createContext()

        import React, { Component } from 'react';
        // Create new context
        export const MyContext = React.createContext();
    
        export class MyProvider extends Component {
    
            render() {
                const contextValue={state: { items: [] }, actions: { doA: () => {}}}
    
                return (
                    <MyContext.Provider value={contextValue}>
                       .....
                    </MyContext.Provider>
                )
            }
        }
    
        2
  •  0
  •   Chen    7 年前

    更新:

    显然这是第三方的问题。我使用了google map react库,注意到他们取消了对使用react版本<15的用户的上下文API的支持,并在下一个主要版本上发布了补丁。