带有功能组件的React JS Context API不工作



我正在做一个React JS项目,该项目使用上下文API、React钩子和功能组件。现在我正在尝试创建一个上下文提供程序,并尝试更改来自子组件的状态。但它并没有如预期的那样发挥作用。这就是我迄今为止所做的。

我已经创建了具有以下定义的上下文提供程序组件。

import React, { Component } from 'react';
const { Provider, Consumer } = React.createContext({ currentLan: 'en' });
class LangContextProvider extends Component {
state = {
currentLan: 'en'
}
switchLang = () => {
this.setState({
currentLan: this.state.currentLan == 'it'? 'en': 'it',
})
}
render() {
return <Provider value={this.state}>{this.props.children}</Provider>
}
}
export { LangContextProvider, Consumer as LangContextConsumer };

请注意switchLang函数,因为我正试图从子组件调用它来更新状态。

这是我的子组件,带有一个更新提供程序状态的按钮。

const SwitchLangButton = () => {
return (
<LangContextConsumer>
{langContext => (
<button onClick=() => { langContext.switchLang() }>Switch lang</button>)
}  
</LangContextConsumer>
)
}

正如你所看到的,当点击按钮切换语言时,我正在调用switchLang函数。

我将我的应用程序与提供商包装如下。

<LangContextProvider>
<React.Fragment>
<App />
</React.Fragment>
</LangContextProvider>

当我点击按钮时,我得到了以下错误。

Uncaught TypeError: langContext.switchLang is not a function

我的代码出了什么问题?

您需要传递switchLang函数:

<Provider value={{currentLan: this.state.currentLan, switchLang}}>{this.props.children}</Provider>

最新更新