尝试执行使用上下文传递给组件的函数

trying to execute a function that is passed to a component using context

我正在尝试学习 context in react, I am trying to pass a function that closes the current user session to a component using context, I am following the context guide in the Updating Context from a Nested Component 部分的概念,但是当单击注销按钮时,我收到以下消息 Expected onClick listener to be a function, instead got a value of object type.

代码如下

我创建了一个空函数作为默认值的上下文

const LogoutContext = React.createContext(() => {});

Root 组件具有调用注销处理程序的状态 属性,我将整个状态作为 Provider 值传递,正如我在文档中读到的那样

class Root extends Component {
  constructor(props) {
    super(props);

    this.state = {
      username: null,
      password: null,
      currentUsername: null,
      logout: this.handleLogout 
    };

    this.handleLogout = () => {
      this.setState({ currentUsername: null });
    };    
  }

  render() {
    const currentUsername = this.state.currentUsername;

    if (currentUsername) {
      return (
        <LogoutContext.Provider value={this.state}>
          <Dashboard username={currentUsername} />
        </LogoutContext.Provider>
      );
    }

    return (
      <Login />
    );
  }
}

仪表板组件呈现 Navbar 组件,该组件使用我需要执行的上下文接收函数

function Dashboard(props) {
  return (
    <div>
      <Navbar />
      <Main />
    </div>
  );
}

在目标组件中,我希望通过单击注销按钮来执行该功能,但我却收到了提到的错误消息

function Navbar(props) {
  return (
    <LogoutContext.Consumer>
      {logout => (
        <nav>
          <ul>
            <li>
              <button onClick={logout}>Logout</button>
            </li>
          </ul>
        </nav>
      )}
    </LogoutContext.Consumer>
  );
}

谢谢你的意见

有 2 个问题首先,您将整个状态对象作为上下文提供程序的值传递,而您似乎只想传递注销函数。其次,注销 属性 是在定义 this.handleLogout 之前设置的状态,因此它的值应该是未定义的。

状态应该只用于在组件的生命周期过程中会发生变化的值。简单的解决方法是从状态中删除注销并将 this.handleLogout 作为上下文值传递。