[英]Local state does not re-render the component when using useLocalStorage
I have a following component我有以下组件
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>
}
Here, I am trying to show , the less and more functionality.在这里,我试图展示越来越少的功能。 In this component, when I click on show more then it function gets called onclick but after that the rerender does not happen.
在这个组件中,当我点击显示更多然后它函数被调用 onclick 但之后不会发生重新渲染。 So, returned div does not get rendered.
因此,返回的 div 不会被渲染。
Can any one help me wit this ?任何人都可以帮我解决这个问题吗?
You need to wrap your component with observer
decorator (or HOC, whatever you want to call it).您需要使用
observer
装饰器(或 HOC,无论您想怎么称呼它)来包装您的组件。
import { observer } from "mobx-react"
const ReadMore = observer(({ comment }) => {
const state = useLocalStore(() => ({
// Your other code here
})
Basically every time you use observable inside component you need to do that so component could react to observable
changes.基本上每次在组件内部使用 observable 时,您都需要这样做,以便组件可以对
observable
变化做出反应。
More info here https://mobx.js.org/refguide/observer-component.html#using-context-to-pass-observables-around更多信息在这里https://mobx.js.org/refguide/observer-component.html#using-context-to-pass-observables-around
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.