javascript - 如何访问 react Context.Provider 值中的另一个函数?
问题描述
目前,我正在学习如何使用 React context API。我有一个 react Provider 类,其中包含一些状态数据和函数value={}
。如何从该值内的另一个函数访问该值内的函数?
因此,function1()
由子组件调用。状态更改完成后,我想调用function2()
并访问新状态。
是否有可能做出这样的反应?:
class Provider extends Component {
state = {
foo: 'bar'
}
render() {
return() {
<Context.Provider value={{
state: this.state,
function1: () => {
this.setState({ foo: 'changed' }, () => {
// HERE I WANT TO CALL THE NEXT FUNCTION IN THIS VALUE
this.function2()
});
},
function2: () => {
// called by function1 after state change
console.log(this.state)
}
}}>
{ this.props.children }
</Context.Provider>
}
}
}
如果我尝试运行它并function1()
从孩子身上解雇它,它会给我
TypeError: _this2.function2() is not a function
我不明白,为什么它试图访问一个_this2
变量,因为我将它定义为 access this.function2()
。
在反应中做我想做的事是不可能的吗?你可能会说,为什么function2()
是一个额外的函数,为什么我不在function1()
. 这是因为function2()
必须是一个独立的可访问函数。
谁能帮我?谢谢!
解决方案
你可以尝试做的是: -
class Provider extends Component {
state = {
foo: 'bar'
}
an_independent_function() {
console.log(this.state);
}
render() {
return() {
<Context.Provider value={{
state: this.state,
function1: () => {
this.setState({ foo: 'changed' }, () => {
// HERE I WANT TO CALL THE NEXT FUNCTION IN THIS VALUE
this.an_independent_function();
});
},
function2: this.an_independent_function.bind(this)
}}>
{ this.props.children }
</Context.Provider>
}
}
}
推荐阅读
- java - Leetcode #11 装水最多的容器:为什么要使用“else”
- kubernetes - 我在 gitlab 中的自动 devops 管道不起作用
- php - 通过维基数据获取比利时的城市列表
- mysql - 当使用触发器更改另一个字段时,从表中更改字段的值
- python - 确定每组的连续日期期间
- excel - 将所有 pdf 文件移动到新文件夹
- laravel - 在 laravel 上使用 like 无法显示日期搜索
- python - Python列表根据文本获取唯一元素
- mysql - Tomcat 8.5 连接池在数据库故障转移后未重新连接
- javascript - 如何使用颜色选择器更改 3D Sierpinski 垫片每一侧的颜色?