首页 > 解决方案 > 自定义 Hook 和级联下拉菜单

问题描述

我是新手,我正在边做边学。现在我正在使用自定义 Hook 在组件之间共享逻辑。

这是自定义 Hook 内部的逻辑

const useDropDownLogic = () => {
    const { menu } = useContext(MenuContext)
    const brand = [...new Set(menu.map(i => i.brand))]
    const [category, setCategory] = useState([])

    const brandChange = (e) => {
        const { type, textContent } = e.target
        setCategory([...new Set(menu.filter(i => i.[type] == textContent).map(i => i.category))])}

    return {
        brandChange, 
        brand, 
        category
    }
}
 
export default useDropDownLogic;

这是使用自定义 Hook 的第一个组件

const DropDownBrand = () => {
  const {brandChange, brand} = useDropDownLogic();
  const dropdownRef = useRef(null);
  const [isActive, setIsActive] = useDetectOutsideClick(dropdownRef, false);
  const onClick = () => setIsActive(!isActive)

  return (
    <div id="dropdownbrand">
      <div className="menu-container menu-brand">
        <label className = 'nav-label'>Select a Brand</label>
        <button onClick={onClick} className="menu-trigger brand-btn">
        <i className="fas fa-chevron-down fa-2x drop-arrow"></i>
        </button>
        <nav
          ref={dropdownRef}
          className={`drop-menu ${isActive ? "active" : "inactive"}`}
        >
          <ul>
          {brand.map((i) => (<li key={nanoid()} type = 'brand' value={i} onClick = {(e) => brandChange(e)}>{i}</li>))}
          </ul>
        </nav>
      </div>
    </div>
  );
};

导出默认 DropDownBrand;

这是第二个

    const DropDownCategory = () => {
  const { category } = useDropDownLogic()
  const dropdownRef = useRef(null);
  const [isActive, setIsActive] = useDetectOutsideClick(dropdownRef, false);
  const onClick = () => setIsActive(!isActive)

console.log(category);
  return (
    <div id="dropcategory">
      <div className="menu-container menu-brand">
        <label className = 'nav-label'>Select a Brand</label>
        <button onClick={onClick} className="menu-trigger brand-btn">
        <i className="fas fa-chevron-down fa-2x drop-arrow"></i>
        </button>
        <nav
          ref={dropdownRef}
          className={`drop-menu ${isActive ? "active" : "inactive"}`}
        >
          <ul>
          {category.map((i) => (<li key={nanoid()} type = 'category'>{i}</li>))}
          </ul>
        </nav>
      </div>
    </div>
  );
};

export default DropDownCategory;

基本上我可以填充第一个下拉列表,但不能填充第二个。我不明白为什么类别状态没有更新到 DropDownCategory 组件中

任何提示我做错了什么?

提前谢谢了

标签: reactjsreact-hooksdropdowncascading

解决方案


I see,

I'm changing the approach. Moving state to a parent component and passing down function to handle click event. Then on Parent I'll update the dstate and pass it as props down to the child. Nyhting to share yet but it will come


推荐阅读