![](/img/trans.png)
[英]Re-render problem when using react custom hook useLocalStorage in sibling component
[英]Local state does not re-render the component when using useLocalStorage
我有以下組件
const showMoreDom = (text, onClick) => {
return (
<div>
{text}
<span className='anchor' onClick={onClick}>
{' '}
show more{' '}
</span>
</div>
)
}
const showLessDom = (text, onClick) => {
return (
<div>
{text}
<span className='anchor' onClick={onClick}>
{' '}
show less{' '}
</span>
</div>
)
}
export const ReadMore: React.FunctionComponent<IReadMore> = ({ comment }) => {
const state = useLocalStore(() => ({
isShowLess: false,
handleShowLess: () => {
state.isShowLess = false
},
handleShowMore: () => {
state.isShowLess = true
}
}))
const text = comment || ''
const maxLength = MAX_LENGTH
const textLength = text.length
if (textLength > maxLength && !state.isShowLess) {
const clippedText = text.slice(0, 14) + '...'
return showMoreDom(clippedText, state.handleShowMore)
}
if (state.isShowLess) {
const overflownText = text
return showLessDom(overflownText, state.handleShowLess)
}
return <Typography className={classNames({})}>{text}</Typography>
}
在這里,我試圖展示越來越少的功能。 在這個組件中,當我點擊顯示更多然后它函數被調用 onclick 但之后不會發生重新渲染。 因此,返回的 div 不會被渲染。
任何人都可以幫我解決這個問題嗎?
您需要使用observer
裝飾器(或 HOC,無論您想怎么稱呼它)來包裝您的組件。
import { observer } from "mobx-react"
const ReadMore = observer(({ comment }) => {
const state = useLocalStore(() => ({
// Your other code here
})
基本上每次在組件內部使用 observable 時,您都需要這樣做,以便組件可以對observable
變化做出反應。
更多信息在這里https://mobx.js.org/refguide/observer-component.html#using-context-to-pass-observables-around
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.