如何在React Hooks中修改prop并将其设置为初始状态?

I get a prop text, which is string. I need to trim this text and pass it to component state. How to do this? In the old way I could use componentDidMount function. Now I try with useEffect() hook but it doesn't work. "Cannot read property 'substring' of null". What am I doing wrong?

export const ReadMore: React.FC<IReadMoreProps> = ({
 text, characterLimit,
}) => {

const [textValue, trimText] = useState(text);

useEffect(() => {
  trimText(text.substring(0, characterLimit));
});

return (
  <>
   {textValue}
  </>
 );
};
评论
  • uid
    uid 回复

    在这种情况下,您不需要状态。你可以做这样的事情。

    export const ReadMore: React.FC<IReadMoreProps> = ({
     text, characterLimit,
    }) => {
    
    const textValue = (text || "").substring(0, characterLimit);
    return (
      <>
       {textValue}
      </>
     );
    };