简体   繁体   中英

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. So, returned div does not get rendered.

Can any one help me wit this ?

You need to wrap your component with observer decorator (or HOC, whatever you want to call it).

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.

More info here https://mobx.js.org/refguide/observer-component.html#using-context-to-pass-observables-around

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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