这个react useState挂钩有什么问题?

时间:2020-03-23 09:34:06

标签: reactjs react-hooks

我在线上找到了该组件,该组件创建了一个审阅组件,但无法正常工作。

import { useState } from 'react';

const Star = ({filled, starId}) => (
  <span star-id={starId} style={{ color: '#ff9933' }} role="button">
  {filled ? '\u2605' : '\u2606'}
</span>
);

export const Rating = props => (
  const [rating, setRating] = useState(typeof props.rating == 'number' ? props.rating : 0);
  const [selection, setSelection] = useState(0);
  const hoverOver = event => {
    let val = 0;
    if (event && event.target && event.target.getAttribute('star-id'))
      val = event.target.getAttribute('star-id');
    setSelection(val);
  };
  return (
    <div
      onMouseOut={() => hoverOver(null)}
      onClick={event => setRating(event.target.getAttribute('star-id') || rating)}
      onMouseOver={hoverOver}
    >
      {Array.from({ length: 5 }, (v, i) => (
        <Star
          starId={i + 1}
          key={`star_${i + 1} `}
          filled={selection ? selection >= i + 1 : rating >= i + 1}
        />
      ))}
    </div>
  );

此行抛出错误:

 const [rating, setRating] = useState(typeof props.rating == 'number' ? props.rating : 0);

这有什么问题?以及如何解决?

1 个答案:

答案 0 :(得分:2)

我认为该钩子很好,但是您需要在函数主体周围使用{}

export const Rating = props => {
    const [rating, setRating] = useState((typeof props.rating === 'number') ? props.rating : 0);
    const [selection, setSelection] = useState(0);
    const hoverOver = event => {
        let val = 0;
        if (event && event.target && event.target.getAttribute('star-id'))
            val = event.target.getAttribute('star-id');
        setSelection(val);
    };
    return (
        <div
        onMouseOut={() => hoverOver(null)}
        onClick={event => setRating(event.target.getAttribute('star-id') || rating)}
        onMouseOver={hoverOver}
        >
            {Array.from({ length: 5 }, (v, i) => (
            <Star
            starId={i + 1}
            key={`star_${i + 1} `}
            filled={selection ? selection >= i + 1 : rating >= i + 1}
            />
            ))}
        </div>
    );
};

codesandbox

您应该考虑的第二件事:您可能应该使用===而不是==来进行typeof检查。