Javascript 从React上下文don';I don’我没有按预期工作
以下是我的上下文设置:Javascript 从React上下文don';I don’我没有按预期工作,javascript,reactjs,react-context,Javascript,Reactjs,React Context,以下是我的上下文设置: export const myContext = Rect.CreateContext({ strings:[], addString(newString){ this.strings.push(newString) } }) 在我的一个嵌套组件中,我尝试执行以下操作: class myComponent extends Component{ static contextType = myContext; myFunction(){ cons
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
?在您的解构结构上,您缺少字符串中的“r”
试一试
应该是
this.strings.push()
不是吗?正如您在context@CodeManiac对不起,这是我的错别字,问题仍然有效。您从上下文中提取了{addSting}
,但您正在调用addString。我想应该是{addString}
。对不起,那是个打字错误,我在问题中更正了
const {addString} = this.context