反应useState()和useContext()-类型错误:setState不是函数-我在做什么错?

时间:2020-05-01 09:35:22

标签: reactjs react-native react-hooks react-state

我有一些我想共享状态的React功能组件。在此示例中,有两个切换按钮可以有条件地显示/隐藏搜索栏和导航栏。

-解决方案,基于接受的答案,在底部-

我是useContext()的新手,并且在控制台中不断遇到以下错误: Uncaught TypeError: setSearchbarToggle is not a function适用于两个按钮。

下面我有一个经过过滤的示例代码。仅作为示例,我在一个文件中使用状态。在现实生活中,我会在多个功能组件中重用状态。

这是我的header.js

import React, { useState, useContext } from "react"
import "./header.sass"
import { Context } from "./HeaderContext"

export const Header = () => {

  const headerContext = useContext(Context)
  const { navbarToggle, setNavbarToggle, searchbarToggle, setSearchbarToggle } = headerContext

  return (
    <React.Fragment>
      <div className={"sticky-top"}>

        <button onClick={ () => setNavbarToggle( !navbarToggle )}> Toggle Menu </button>
        <button onClick={ () => setSearchbarToggle( !searchbarToggle )}> Toggle Search </button>

        {navbarToggle && <h3>Menu is showing</h3>}
        {searchbarToggle && <h3>Searchbar is showing</h3>}

      </div>
    </React.Fragment>
  )
}
export default Header

这是我的HeaderContext.jsx

import React, { createContext, useState } from "react";
import PropTypes from "prop-types";

export const Context = createContext({});

export const Provider = props => {
  const {
    navbarToggle: initialNavBarToggle,
    searchbarToggle: initialSarchbarToggle,
    children
  } = props;
  
  const [navbarToggle, setNavbarToggle] = useState(initialNavBarToggle);
  const [searchbarToggle, setSearchbarToggle] = useState(initialSarchbarToggle);

  const headerContext = {
    navbarToggle, setNavbarToggle,
    searchbarToggle, setSearchbarToggle
  };

  return <Context.Provider value={headerContext}>{children}</Context.Provider>;
};

export const { Consumer } = Context;

Provider.propTypes = {
  navbarToggle: PropTypes.bool,
  searchbarToggle: PropTypes.bool
};

Provider.defaultProps = {
  navbarToggle: false,
  searchbarToggle: false
};

我希望你能对此有所启发

-编辑-

这是我基于接受答案的代码。

import React, { useContext } from "react"
import { Provider,Context } from "./HeaderContext"

export const HeaderWithContext= () => {

  const headerContext = useContext(Context)
  const { navbarToggle, setNavbarToggle, searchbarToggle, setSearchbarToggle } = headerContext

  return (
    <React.Fragment>
      <div className={"sticky-top"}>

        <button onClick={ () => setNavbarToggle( !navbarToggle )}> Toggle Menu </button>
        <button onClick={ () => setSearchbarToggle( !searchbarToggle )}> Toggle Search </button>

        {navbarToggle && <h3>Menu is showing</h3>}
        {searchbarToggle && <h3>Searchbar is showing</h3>}

      </div>
    </React.Fragment>
  )
}

export const Header = () => {
  return (
    <Provider>
      <HeaderWithContext/>
    </Provider>
  )
};

1 个答案:

答案 0 :(得分:2)

父级组件之一,例如应用必须用Context.Provider包装标头(或其始祖组件之一):

import { Provider } from "./HeaderContext"
...
<Provider>
  <Header />
</Provider>