我有一个孙子组件,他们从祖父母那里消费。但是,上下文值未定义:
文件1:
<artifactId>//artifactID</artifactId>
<version>0.0.1-SNAPSHOT</version>
<packaging>jar</packaging>
<name>fraud-core</name>
<description>Demo project for Spring Boot</description>
<parent>
//Parent
</parent>
<properties>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
<project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding>
<java.version>1.8</java.version>
<HMN_CDM_Facade.version>TEST-SNAPSHOT</HMN_CDM_Facade.version>
<hmn.dependency.scope>compile</hmn.dependency.scope>
</properties>
<dependencies>
//DEPENDENCIES
</dependencies>
<build>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
</plugin>
</plugins>
<resources>
<resource>
<directory>src/main/resources</directory>
<filtering>true</filtering>
<includes>
<include>**/*.properties</include>
</includes>
</resource>
</resources>
</build>
文件2:
export const WTContext = createContext();
export default class A extends Component {
...
render(){
...
const contextValue={state: { items: [] }, actions: { doA: () => {}}}
return (
<WTContext.Provider value={contextValue} >
...
</WTContext.Provider>
}
}
}
文件3:
export default function B(){
return (
<WTContext.Consumer>
{({state}) => (
...
return (
<div>
{state.items.map(...<C/>)} //all good, B use context.
</div>
{state.items
)
)}
</WTContext.Consumer>
)
}
因此export default function C(props){
return (
<WTContext.Consumer>
{({ state, actions }) => {
// <-- Cannot read property 'state' of undefined
...
}
</WTContext.Consumer>
)
}
中的呈现多个B
组件的映射具有上下文使用者值C
。
导入是有效的,但是我无法弄清楚提供商在第二层嵌套中传递的值是undefined
的原因(因为第一层看起来不错,undefined
它确实使用上下文作为请求)。
答案 0 :(得分:0)
使用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>
)
}
}
答案 1 :(得分:0)
更新:
显然这是第三方问题。我使用了google-map-react库,并注意到他们为使用React版本<15的用户删除了对Context API的支持,并在下一个主要版本中发布了此修复程序。