从 React Context 命名的导入不能按预期工作

Named import from React Context don't work as expected

这是我的上下文设置:

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 
 }
}

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

在你的解构中你遗漏了字符串

中的 "r"

尝试

const {addString} = this.context