0

当 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,但在 500 毫秒后不会更改为Two,即使它更改了 prop。

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

4

1 回答 1

1

免责声明:我还没有积极地使用 recompose。

但我知道你的组件应该是有状态的。我withState在重组文档中找到

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>
)

所以我认为,您需要使用定义状态msgwithState然后您可以将其传递setMsg到您的组件中。setMsg在您的内部调用它时,setTimeout应该执行更新。

const withMsg = withState('msg', 'setMessage', '');
于 2018-06-06T14:18:09.387 回答