为什么我要进行无效的挂接呼叫?

时间:2020-05-14 14:40:41

标签: javascript reactjs

嗨,我是React的新手,所以请耐心等待。有人可以告诉我为什么要进行无效的挂机呼叫吗?我认为问题是与useState(null)或它所使用的功能有关。下面的代码显示了我正在尝试使用它的全部能力。非常感谢。

import React, { useState } from 'react';
import ScrollMenu from 'react-horizontal-scrolling-menu';
import './horizontalscroll.css';

const data = [
  {
    category: "Brands",
    items: ["Gucci", "Calvin klein", "Prada"]
  },
  {
    category: "Films",
    items: ["Inception ", "Dark Night", "Home Alone"]
  }
];


const [category, setCategory] = useState(null);
const onClick = category => {
    setCategory(category);
  };


// One item component
// selected prop will be passed
const MenuItem = ({ text, selected }) => {
  return (
    <div
      className="menu-item"
    >
      {text}
    </div>
  );
};

// All items component
// Important! add unique key
export const Menu = (list) => list.map(el => {
  const { category } = el;

  return (
    <MenuItem
      text={category}
      key={category}
    />
  );
});


const Arrow = ({ text, className }) => {
  return (
    <div
      className={className}
    >{text}</div>
  );
};


const ArrowLeft = Arrow({ text: '<', className: 'arrow-prev' });
const ArrowRight = Arrow({ text: '>', className: 'arrow-next' });

class HorizantScroller extends React.Component {
  state = {
    selected: 0
  };

  onSelect = key => {
    this.setState({ selected: key });
  }


  render() {
    const { selected } = this.state;
    // Create menu from items
    const menu = Menu(list, selected);

    return (
      <div className="HorizantScroller">
        <ScrollMenu
          data={menu}
          arrowLeft={ArrowLeft}
          arrowRight={ArrowRight}
          selected={selected}
          onSelect={this.onSelect}
          onClick={onClick}
        />
      </div>
    );
  }
}

export default HorizantScroller;



2 个答案:

答案 0 :(得分:4)

挂钩只能在功能组件的主体中使用。这些行位于文件的顶层,根本不在任何组件中:

const [category, setCategory] = useState(null);
const onClick = category => {
  setCategory(category);
};

根据使用onClick的位置,我最好的猜测是希望它成为HorizantScroller组件的状态,但是HorizantScroller是类组件,而不是函数组件,因此您不能使用钩子。

恐怕从提供的信息中我无法提出具体建议,因为目前尚不清楚您要做什么。因此,我建议您确定要使其成为状态的组件。如果该组件是功能组件,请在其中移动代码。如果该组件是类组件,则需要将其转换为功能组件,或者需要使用this.statethis.setState进行状态管理。

答案 1 :(得分:0)

第一件事首先,Hooks在React中发布的主要原因是能够在纯函数中设置内部状态。如果您希望使用react实现状态,我建议您使用纯函数而不是基于类的函数。挂钩react hooks documentation

这是来自文档表单react的示例:

import React, { useState } from 'react';

export default function Example() {
// Declare a new state variable, which we'll call "count"
const [count, setCount] = useState(0);

return (
  <div>
   <p>You clicked {count} times</p>
   <button onClick={() => setCount(count + 1)}>
     Click me
   </button>
  </div>
 );
}

并且要使用基于功能的组件,您可以执行以下操作

import ReactDOM from 'react-dom';
import Example from './example/example.js'
ReactDOM.render(<Example />);