【问题标题】:React JS Context API with functional component is not working带有功能组件的 React JS 上下文 API 不起作用
【发布时间】:2020-09-30 16:46:06
【问题描述】:

我正在开发一个使用上下文 API、React 钩子和功能组件的 React JS 项目。现在。我正在尝试创建一个上下文提供程序并尝试更改来自子组件的状态。但它没有按预期工作。这是我到目前为止所做的。

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

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

我的代码有什么问题?

【问题讨论】:

    标签: reactjs react-hooks react-context


    【解决方案1】:

    需要通过switchLang函数:

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2021-10-10
      • 1970-01-01
      • 2021-04-19
      • 2022-06-11
      • 2020-08-14
      • 2018-04-13
      • 2019-09-01
      • 2020-08-09
      相关资源
      最近更新 更多