【问题标题】:Recompose async prop update重构异步道具更新
【发布时间】:2018-11-16 06:15:33
【问题描述】:

当 prop 从视图组件外部更改时,如何使用 recompose 重新渲染组件?

const Message = ({msg}) => <div>The prop has a value of <b>{msg}</b>.</div>

const App = Recompose.withProps(() => {
  let msg = 'One'

  // this async update doesn't work because nothing triggers a rerender
  setTimeout(() => {msg = 'Two'}, 500)

  return {msg}
})(Message)


ReactDOM.render(<App/>, document.getElementById('app'))

当这个组件被渲染时,它的值显示为 One,但在 500ms 后不会变为 Two,即使它改变了 prop。

这里的setTimeout 简化了在实际用例中我订阅 websocket 服务器并且当消息被推送时,消息组件被更新的情况。

【问题讨论】:

    标签: javascript reactjs recompose


    【解决方案1】:

    免责声明:我还没有主动使用 recompose。

    但我知道你的组件应该是有状态的。我找到了withState in recompose docs

    const enhance = withState('counter', 'setCounter', 0)
    const Counter = enhance(({ counter, setCounter }) =>
      <div>
        Count: {counter}
        <button onClick={() => setCounter(n => n + 1)}>Increment</button>
        <button onClick={() => setCounter(n => n - 1)}>Decrement</button>
      </div>
    )
    

    所以我的想法是,您需要使用withState 定义状态msg,然后您可以将setMsg 传递到您的组件中。在您的setTimeout 中调用此setMsg 时,应执行更新。

    const withMsg = withState('msg', 'setMessage', '');
    

    【讨论】:

      猜你喜欢
      • 2017-10-24
      • 2018-04-04
      • 2021-10-12
      • 1970-01-01
      • 2019-10-31
      • 1970-01-01
      • 2016-06-01
      • 2017-06-01
      • 2021-05-11
      相关资源
      最近更新 更多