首页 > 解决方案 > 从 React Context 命名的导入不能按预期工作

问题描述

这是我的上下文设置:

export const myContext = Rect.CreateContext({
  strings:[],
  addString(newString){
    this.strings.push(newString)
  }
})

在我的一个嵌套组件中,我正在尝试执行以下操作:

class myComponent extends Component{
static contextType = myContext;

 myFunction(){
  const { addSting } = this.context ;

  addString('mystring'); //- this causes "TypeError: Cannot read property 'string' of undefined"

  this.context.addString('mystring'); //- this runs fine 
 }
}

为什么我不能在addString不指定的情况下使用“”方法this.context

标签: javascriptreactjsreact-context

解决方案


在您的解构中,您缺少字符串中的“r”

尝试

const {addString} = this.context

推荐阅读