使用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的更改做出反应。

此处更多信息https://mobx.js.org/refguide/observer-component.html#using-context-to-pass-observables-around

相关问答

错误1:Request method ‘DELETE‘ not supported 错误还原:...
错误1:启动docker镜像时报错:Error response from daemon:...
错误1:private field ‘xxx‘ is never assigned 按Alt...
报错如下,通过源不能下载,最后警告pip需升级版本 Requirem...