简体   繁体   English

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

[英]How to modify prop and set it to initial state in React Hooks?

I get a prop text , which is string.我得到一个道具text ,它是字符串。 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.以旧方式,我可以使用componentDidMount函数。 Now I try with useEffect() hook but it doesn't work.现在我尝试使用useEffect()钩子,但它不起作用。 "Cannot read property 'substring' of null". “无法读取 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}
  </>
 );
};

You don't need state in this case.在这种情况下,您不需要状态。 You can do something like this.你可以做这样的事情。

export const ReadMore: React.FC<IReadMoreProps> = ({
 text, characterLimit,
}) => {
const [showMore, setShowMore] = useState(false);
const textValue = showMore ? text : (text || "").substring(0, characterLimit);
return (
  <>
   {textValue}
  </>
 );
};

I think that may be a type issue.我认为这可能是类型问题。 Try this:尝试这个:

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

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

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

return (
  <>
   {textValue}
  </>
 );
};

Hope this works for you.希望这对你有用。

The problem is outside the code you shared.问题出在您共享的代码之外。 (see sandbox https://codesandbox.io/s/lucid-fire-e3w4w ) (见沙箱https://codesandbox.io/s/lucid-fire-e3w4w

text prop must be null when the component is mounted.安装组件时text prop 必须为 null。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM