Javascript 如何在React钩子中修改道具并将其设置为初始状态?
我得到一个propJavascript 如何在React钩子中修改道具并将其设置为初始状态?,javascript,reactjs,typescript,react-hooks,Javascript,Reactjs,Typescript,React Hooks,我得到一个proptext,它是字符串。我需要修剪此文本并将其传递到组件状态。如何做到这一点?按照旧方法,我可以使用componentDidMount函数。现在我尝试使用useffect()hook,但它不起作用。“无法读取null的属性'substring'。”。我做错了什么 export const ReadMore: React.FC<IReadMoreProps> = ({ text, characterLimit, }) => { const [textValue
text
,它是字符串。我需要修剪此文本并将其传递到组件状态。如何做到这一点?按照旧方法,我可以使用componentDidMount
函数。现在我尝试使用useffect()
hook,但它不起作用。“无法读取null的属性'substring'。”。我做错了什么
export const ReadMore: React.FC<IReadMoreProps> = ({
text, characterLimit,
}) => {
const [textValue, trimText] = useState(text);
useEffect(() => {
trimText(text.substring(0, characterLimit));
});
return (
<>
{textValue}
</>
);
};
export const ReadMore:React.FC=({
文本,字符限制,
}) => {
const[textValue,trimText]=使用状态(text);
useffect(()=>{
trimText(text.substring(0,characterLimit));
});
返回(
{textValue}
);
};
在这种情况下不需要状态。你可以这样做
export const ReadMore: React.FC<IReadMoreProps> = ({
text, characterLimit,
}) => {
const [showMore, setShowMore] = useState(false);
const textValue = showMore ? text : (text || "").substring(0, characterLimit);
return (
<>
{textValue}
</>
);
};
export const ReadMore:React.FC=({
文本,字符限制,
}) => {
const[showMore,setShowMore]=useState(false);
const textValue=showMore?text:(text | |“”).substring(0,characterLimit);
返回(
{textValue}
);
};
我认为这可能是一个类型问题。试试这个:
export const ReadMore: React.FC<IReadMoreProps> = ({
text, characterLimit,
}) => {
const [textValue, trimText] = useState(text);
useEffect(() => {
trimText(text.toString().substring(0, characterLimit));
}, [text]);
return (
<>
{textValue}
</>
);
};
export const ReadMore:React.FC=({
文本,字符限制,
}) => {
const[textValue,trimText]=使用状态(text);
useffect(()=>{
trimText(text.toString().substring(0,characterLimit));
},[正文];
返回(
{textValue}
);
};
希望这对您有用。问题不在您共享的代码范围内。(见沙箱)
安装组件时,文本属性必须为null。看起来您的文本属性为null。请尝试记录您的文本。它不是null。当我删除子字符串方法时,所有内容都会正确呈现。但我希望添加“读取更多”、“读取更少”功能,因此我需要操纵我的状态。你可以拥有该状态并根据该值计算文本。更新了我的答案。